answer
stringlengths 17
10.2M
|
|---|
package com.whispir.api;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.json.JSONException;
import org.json.JSONObject;
import com.whispir.api.exceptions.WhispirAPIException;
/**
* WhispirAPI
*
* Wrapper class to simplify the usage of the Whispir API.
*
* Utilises Apache HTTPClient to post simple messages via JSON.
*
* @author Jordan Walsh
* @version 1.0
*
*/
public class WhispirAPI {
private static final String WHISPIR_MESSAGE_HEADER_V1 = "application/vnd.whispir.message-v1+json";
private static final String WHISPIR_MESSAGE_HEADER_V2 = "application/vnd.whispir.message-v2+json";
private static final String API_HOST = "api.whispir.com";
private static final String API_URL = "https://" + API_HOST + "/";
private static final String API_EXT = "?apikey=";
private static final String NO_AUTH_ERROR = "Whispir API Authentication failed. API Key, Username or Password was not provided.";
private static final String AUTH_FAILED_ERROR = "Whispir API Authentication failed. API Key, Username or Password were provided but were not correct.";
private String apikey;
private String username;
private String password;
private String version;
@SuppressWarnings("unused")
private WhispirAPI() {}
/**
* Instantiates the WhispirAPI object.
*
* Requires the three parameters to be provided. Assumes that this is using the v1 API.
*
* @param apikey
* @param username
* @param password
*/
public WhispirAPI(String apikey, String username, String password) throws WhispirAPIException{
this(apikey, username, password, "v1");
}
/**
* Instantiates the WhispirAPI object.
*
* Requires the four parameters to be provided. Version can be provided in the form "v1" or "v2".
*
* @param apikey
* @param username
* @param password
* @param version
*/
public WhispirAPI(String apikey, String username, String password, String version) throws WhispirAPIException{
if(apikey == null || username == null || password == null || version == null ) {
throw new WhispirAPIException(NO_AUTH_ERROR);
}
if("".equals(apikey) || "".equals(username) || "".equals(password) || "".equals(version)) {
throw new WhispirAPIException(NO_AUTH_ERROR);
}
try {
this.apikey = apikey;
this.username = username;
this.password = password;
//If the GET request fails, then throw an error as the API won't work.
int response = this.testHttpCall();
if (response != 200) {
throw new WhispirAPIException(AUTH_FAILED_ERROR);
}
if("v2".equals(version)) {
this.version = WHISPIR_MESSAGE_HEADER_V2;
} else {
this.version = WHISPIR_MESSAGE_HEADER_V1;
}
} catch (WhispirAPIException e) {
throw e;
}
}
public void setApikey(String apikey) {
this.apikey = apikey;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setVersion(String version) {
this.version = version;
}
/**
* Allows a user to send a message in the default My Company workspace
* @param recipient - the mobile number or email address of the recipient of the message
* @param subject - the textual subject of the message
* @param content - the textual content of the Push/SMS message.
*
* For more complex content, the user should use the Map content overloaded function
*
* @return response - the HTTP response code of the performed action.
*/
public int sendMessage(String recipient, String subject, String content) throws WhispirAPIException{
return sendMessage("", recipient, subject, content);
}
/**
* Allows a user to send a message in the specified Workspace ID
* @param recipient - the mobile number or email address of the recipient of the message
* @param subject - the textual subject of the message
* @param content - the textual content of the Push/SMS message.
*
* For more complex content, the user should use the Map content overloaded function
*
* @return response - the HTTP response code of the performed action.
*/
public int sendMessage(String workspaceId, String recipient, String subject, String content) throws WhispirAPIException{
Map<String,String> smsContent = new HashMap<String,String>();
smsContent.put("body", content);
return sendMessage(workspaceId, recipient, subject, smsContent);
}
/**
* Allows a user to send a message in any workspace, with any combination of content within the content map
* <p>
* The content Map is expected to provide the following information
* </p>
* For SMS/Push
* body - The content for the Push/SMS message
*
*
* @param recipient - the mobile number or email address of the recipient of the message
* @param subject - the textual subject of the message
* @param content - the Map of content for the Whispir Message
* @return response - the HTTP response code of the performed action.
*/
public int sendMessage(String workspaceId, String recipient, String subject, Map<String,String> content) throws WhispirAPIException{
Map<String, String> options = new HashMap<String, String>();
return sendMessage(workspaceId, recipient, subject, content, options);
}
/**
* Allows a user to send a message in any workspace, with any combination of content within the content map
* <p>The content Map is expected to provide the following information:</p>
* <p>For SMS/Push</p>
* <p>- body - The content of the SMS/Push Message</p>
* <p></p>
* <p>The options Map is expected to provide the following information:</p>
* <p>- type - defaultNoReply (specifies if the message cannot be replied to)</p>
* <p>- pushEscalation - true/false (string)</p>
* <p>- escalationMins - 3,4,5,10 (string)</p>
* <p></p>
* @param recipient - the mobile number or email address of the recipient of the message
* @param subject - the textual subject of the message
* @param content - the Map of content for the Whispir Message
* @param options - the Map of options for the Whispir Message
* @return response - the HTTP response code of the performed action.
*/
public int sendMessage(String workspaceId, String recipient, String subject, Map<String,String> content, Map<String,String> options) throws WhispirAPIException{
int response = 0;
if(recipient == null || recipient.length() < 8) {
//error with the recipient information, returning HTTP 422.
return 422;
}
try {
JSONObject request = new JSONObject();
request.put("to", recipient);
request.put("subject", subject);
//Check for the body in the map
if(content.containsKey("body") && !"".equals(content.get("body"))) {
request.put("body", content.get("body"));
}
//Check for the options in the map
if(options.containsKey("type")) {
request.put("type", options.get("type"));
}
response = httpPost(workspaceId, request.toString());
} catch (JSONException e) {
throw new WhispirAPIException("Error occurred parsing the object with the content provided." + e.getMessage());
} catch (Exception e) {
throw new WhispirAPIException("Error occurred." + e.getMessage());
}
return response;
}
private int testHttpCall() throws WhispirAPIException {
OptionsMethod method = (OptionsMethod)createOptionsMethod();
return executeHttpMethod(method);
}
private int httpPost(String workspace, String jsonContent) throws WhispirAPIException {
PostMethod method = (PostMethod)createPostMethod(workspace, jsonContent);
return executeHttpMethod(method);
}
private int executeHttpMethod(HttpMethod method) throws WhispirAPIException {
int statusCode = 0;
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
client.getState().setCredentials(
new AuthScope(API_HOST, -1),
new UsernamePasswordCredentials(this.username, this.password));
try {
statusCode = client.executeMethod(method);
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
return statusCode;
}
private HttpMethod createPostMethod(String workspaceId, String content) throws WhispirAPIException {
// Create a method instance.
String url = "";
RequestEntity request;
if(workspaceId != null && !"".equals(workspaceId)) {
url = API_URL + "workspaces/" + workspaceId + "/messages" + API_EXT + this.apikey;
} else {
url = API_URL + "messages" + API_EXT + this.apikey;
}
PostMethod method = new PostMethod(url);
method.setDoAuthentication(true);
method.setRequestHeader("Content-Type", this.version);
method.setRequestHeader("Accept", this.version);
try {
request = new StringRequestEntity(content, WHISPIR_MESSAGE_HEADER_V1, null);
method.setRequestEntity(request);
} catch (UnsupportedEncodingException e) {
throw new WhispirAPIException(e.getMessage());
}
return method;
}
/**
* Constructs an OPTIONS call to execute with the supplied credentials.
* This is used as a quick test call to determine whether the credentials are correct.
*
* @return OptionsMethod to be executed by HTTPClient
*/
private HttpMethod createOptionsMethod() {
// Create a method instance.
final String url = API_URL + "messages" + API_EXT + this.apikey;
OptionsMethod method = new OptionsMethod(url);
method.setDoAuthentication(true);
method.setRequestHeader("Content-Type", WHISPIR_MESSAGE_HEADER_V1);
method.setRequestHeader("Accept", WHISPIR_MESSAGE_HEADER_V1);
return method;
}
}
|
/*
* $Log: Adapter.java,v $
* Revision 1.43 2008-06-19 11:08:59 europe\L190409
* GALM message when exception caught starting adapter
*
* Revision 1.42 2008/06/18 12:27:43 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* discern between severe errors and warnings (for monitoring)
*
* Revision 1.41 2008/05/21 10:56:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* modified monitorAdapter interface
* fixed NDC handling
*
* Revision 1.40 2008/05/14 09:33:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* simplified methodnames of StatisticsKeeperIterationHandler
* now implements interface HasStatistics
*
* Revision 1.39 2008/03/28 14:20:42 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* simplify error messages
*
* Revision 1.38 2008/03/27 11:09:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* avoid nested non-informative NDCs
*
* Revision 1.37 2008/01/03 15:40:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* renamed start and stop threads
* do not wait at end of start thread
*
* Revision 1.36 2007/12/28 12:01:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* log error messages in request-reply logging
*
* Revision 1.35 2007/12/12 09:08:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added message class to monitor event from error
*
* Revision 1.34 2007/12/10 10:00:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added monitoring
*
* Revision 1.33 2007/10/10 09:35:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Direct copy from Ibis-EJB:
* spring enabled version
*
* Revision 1.32 2007/10/08 12:15:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* corrected date formatting
*
* Revision 1.31 2007/07/24 08:05:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added targetDesignDocument attribute
*
* Revision 1.30 2007/07/10 07:11:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* logging improvements
*
* Revision 1.29 2007/06/26 12:05:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* tuned logging
*
* Revision 1.28 2007/05/02 11:23:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added attribute 'active'
*
* Revision 1.27 2007/03/14 12:22:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* log results in case of exception, too
*
* Revision 1.26 2007/02/12 13:44:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Logger from LogUtil
*
* Revision 1.25 2006/09/14 14:58:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added getPipeLine()
*
* Revision 1.24 2006/09/07 08:35:50 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added requestReplyLogging
*
* Revision 1.23 2006/08/22 12:50:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* moved code for userTransaction to JtaUtil
*
* Revision 1.22 2006/02/09 07:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* name, upSince and lastMessageDate in statistics-summary
*
* Revision 1.21 2005/12/28 08:34:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* introduced StatisticsKeeper-iteration
*
* Revision 1.20 2005/10/26 13:16:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added second default for UserTransactionUrl
*
* Revision 1.19 2005/10/17 08:51:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made getMessageKeeper synchronized
*
* Revision 1.18 2005/08/17 08:12:45 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* NDC updated
*
* Revision 1.17 2005/08/16 12:33:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added NDC with correlationId
*
* Revision 1.16 2005/07/05 12:27:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added possibility to end processing with an exception
*
* Revision 1.15 2005/01/13 08:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* Make threadContext-attributes available in PipeLineSession
*
* Revision 1.14 2004/09/08 14:14:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* adjusted error logging
*
* Revision 1.13 2004/08/19 07:16:21 unknown <unknown@ibissource.org>
* Resolved problem of hanging adapter if stopRunning was called just after the
* adapter was set to started
*
* Revision 1.12 2004/07/06 07:00:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* configure now throws less exceptions
*
* Revision 1.11 2004/06/30 10:02:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved error reporting
*
* Revision 1.10 2004/06/16 13:08:11 Johan Verrips <johan.verrips@ibissource.org>
* Added configuration error when no pipeline was configured
*
* Revision 1.9 2004/06/16 12:34:46 Johan Verrips <johan.verrips@ibissource.org>
* Added AutoStart functionality on Adapter
*
* Revision 1.8 2004/04/28 08:31:41 Johan Verrips <johan.verrips@ibissource.org>
* Added getRunStateAsString function
*
* Revision 1.7 2004/04/13 11:37:13 Johan Verrips <johan.verrips@ibissource.org>
* When the Adapter was in state "ERROR", it could not be stopped anymore. Fixed it.
*
* Revision 1.6 2004/04/06 14:52:52 Johan Verrips <johan.verrips@ibissource.org>
* Updated handling of errors in receiver.configure()
*
* Revision 1.5 2004/03/30 07:29:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* updated javadoc
*
* Revision 1.4 2004/03/26 10:42:45 Johan Verrips <johan.verrips@ibissource.org>
* added @version tag in javadoc
*
*/
package nl.nn.adapterframework.core;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter;
import nl.nn.adapterframework.monitoring.EventTypeEnum;
import nl.nn.adapterframework.monitoring.IMonitorAdapter;
import nl.nn.adapterframework.monitoring.MonitorAdapterFactory;
import nl.nn.adapterframework.monitoring.SeverityEnum;
import nl.nn.adapterframework.receivers.ReceiverBase;
import nl.nn.adapterframework.util.DateUtils;
import nl.nn.adapterframework.util.HasStatistics;
import nl.nn.adapterframework.util.LogUtil;
import nl.nn.adapterframework.util.MessageKeeper;
import nl.nn.adapterframework.util.RunStateEnum;
import nl.nn.adapterframework.util.RunStateManager;
import nl.nn.adapterframework.util.StatisticsKeeper;
import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.springframework.beans.factory.NamedBean;
import org.springframework.core.task.TaskExecutor;
/**
* The Adapter is the central manager in the IBIS Adapterframework, that has knowledge
* and uses {@link IReceiver IReceivers} and a {@link PipeLine}.
*
* <b>responsibility</b><br/>
* <ul>
* <li>keeping and gathering statistics</li>
* <li>processing messages, retrieved from IReceivers</li>
* <li>starting and stoppping IReceivers</li>
* <li>delivering error messages in a specified format</li>
* </ul>
* All messages from IReceivers pass through the adapter (multi threaded).
* Multiple receivers may be attached to one adapter.<br/>
* <br/>
* The actual processing of messages is delegated to the {@link PipeLine}
* object, which returns a {@link PipeLineResult}. If an error occurs during
* the pipeline execution, the state in the <code>PipeLineResult</code> is set
* to the state specified by <code>setErrorState</code>, which defaults to "ERROR".
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>className</td><td>nl.nn.adapterframework.pipes.AbstractPipe</td><td> </td></tr>
* <tr><td>{@link #setName(String) name}</td><td>name of the Adapter</td><td> </td></tr>
* <tr><td>{@link #setDescription(String) description}</td><td>description of the Adapter</td><td> </td></tr>
* <tr><td>{@link #setAutoStart(boolean) autoStart}</td><td>controls whether Adapters starts when configuration loads</td><td>true</td></tr>
* <tr><td>{@link #setActive(boolean) active}</td> <td>controls whether Adapter is included in configuration. When set <code>false</code> or set to something else as "true", (even set to the empty string), the receiver is not included in the configuration</td><td>true</td></tr>
* <tr><td>{@link #setErrorMessageFormatter(String) errorMessageFormatter}</td><td> </td><td> </td></tr>
* <tr><td>{@link #setErrorState(String) errorState}</td><td>If an error occurs during
* the pipeline execution, the state in the <code>PipeLineResult</code> is set to this state</td><td>ERROR</td></tr>
* <tr><td>{@link #setMessageKeeperSize(int) messageKeeperSize}</td><td>number of message displayed in IbisConsole</td><td>10</td></tr>
* <tr><td>{@link #setRequestReplyLogging(boolean) requestReplyLogging}</td><td>when <code>true</code>, the request and reply messages will be logged for each request processed</td><td>false</td></tr>
* </table></td><td> </td></tr>
* </table>
*
* @version Id
* @author Johan Verrips
* @see nl.nn.adapterframework.core.IReceiver
* @see nl.nn.adapterframework.core.PipeLine
* @see nl.nn.adapterframework.util.StatisticsKeeper
* @see nl.nn.adapterframework.util.DateUtils
* @see nl.nn.adapterframework.util.MessageKeeper
* @see nl.nn.adapterframework.core.PipeLineResult
*
*/
public class Adapter implements IAdapter, NamedBean {
public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.43 $ $Date: 2008-06-19 11:08:59 $";
private Logger log = LogUtil.getLogger(this);
private String name;
private String targetDesignDocument;
private boolean active=true;
private Vector receivers = new Vector();
private long lastMessageDate = 0;
private PipeLine pipeline;
private long numOfMessagesProcessed = 0;
private long numOfMessagesInError = 0;
private StatisticsKeeper statsMessageProcessingDuration = null;
private long statsUpSince = System.currentTimeMillis();
private IErrorMessageFormatter errorMessageFormatter;
private RunStateManager runState = new RunStateManager();
private boolean configurationSucceeded = false;
private String description;
private MessageKeeper messageKeeper; //instantiated in configure()
private int messageKeeperSize = 10; //default length
private boolean autoStart = true;
private boolean requestReplyLogging = false;
// state to put in PipeLineResult when a PipeRunException occurs;
private String errorState = "ERROR";
/**
* The nummer of message currently in process
*/
private int numOfMessagesInProcess = 0;
private IMonitorAdapter monitorAdapter=null;
private TaskExecutor taskExecutor;
/**
* Indicates wether the configuration succeeded.
* @return boolean
*/
public boolean configurationSucceeded() {
return configurationSucceeded;
}
/*
* This function is called by Configuration.registerAdapter,
* to make configuration information available to the Adapter. <br/><br/>
* This method also performs
* a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes.
* @see nl.nn.adapterframework.core.Pipeline#configurePipes
*/
public void configure() throws ConfigurationException {
configurationSucceeded = false;
log.debug("configuring adapter [" + getName() + "]");
MessageKeeper messageKeeper = getMessageKeeper();
statsMessageProcessingDuration = new StatisticsKeeper(getName());
if (pipeline == null) {
String msg = "No pipeline configured for adapter [" + getName() + "]";
messageKeeper.add(msg);
throw new ConfigurationException(msg);
}
try {
pipeline.setAdapter(this);
pipeline.configurePipes();
messageKeeper.add("pipeline successfully configured");
Iterator it = receivers.iterator();
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
log.info("Adapter [" + name + "] is initializing receiver [" + receiver.getName() + "]");
receiver.setAdapter(this);
try {
receiver.configure();
messageKeeper.add("receiver [" + receiver.getName() + "] successfully configured");
} catch (ConfigurationException e) {
error(true, "error initializing receiver [" + receiver.getName() + "]",e);
}
}
monitorAdapter=MonitorAdapterFactory.getMonitorAdapter();
configurationSucceeded = true;
}
catch (ConfigurationException e) {
error(true, "error initializing pipeline", e);
}
}
/**
* sends a warning to the log and to the messagekeeper of the adapter
*/
protected void warn(String msg) {
log.warn("Adapter [" + getName() + "] "+msg);
getMessageKeeper().add("WARNING: " + msg);
}
/**
* sends a warning to the log and to the messagekeeper of the adapter
*/
protected void error(boolean critical, String msg, Throwable t) {
log.error("Adapter [" + getName() + "] "+msg, t);
getMessageKeeper().add("ERROR: " + msg+": "+t.getMessage());
String prefix=critical?"ADPTERROR ":"ADPTWARN ";
fireMonitorEvent(EventTypeEnum.TECHNICAL,critical?SeverityEnum.CRITICAL:SeverityEnum.WARNING, prefix+msg,t);
}
protected void fireMonitorEvent(EventTypeEnum eventType, SeverityEnum severity, String message, Throwable t) {
if (monitorAdapter!=null) {
monitorAdapter.fireEvent(getName(), eventType, severity, message, t);
}
}
/**
* Increase the number of messages in process
*/
private void incNumOfMessagesInProcess(long startTime) {
synchronized (statsMessageProcessingDuration) {
numOfMessagesInProcess++;
lastMessageDate = startTime;
}
}
/**
* Decrease the number of messages in process
*/
private synchronized void decNumOfMessagesInProcess(long duration) {
synchronized (statsMessageProcessingDuration) {
numOfMessagesInProcess
numOfMessagesProcessed++;
statsMessageProcessingDuration.addValue(duration);
notifyAll();
}
}
/**
* The number of messages for which processing ended unsuccessfully.
*/
private void incNumOfMessagesInError() {
synchronized (statsMessageProcessingDuration) {
numOfMessagesInError++;
}
}
public synchronized String formatErrorMessage(
String errorMessage,
Throwable t,
String originalMessage,
String messageID,
INamedObject objectInError,
long receivedTime) {
if (errorMessageFormatter == null) {
errorMessageFormatter = new ErrorMessageFormatter();
}
// you never can trust an implementation, so try/catch!
try {
String formattedErrorMessage= errorMessageFormatter.format(
errorMessage,
t,
objectInError,
originalMessage,
messageID,
receivedTime);
if (isRequestReplyLogging()) {
log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]");
} else {
if (log.isDebugEnabled()) {
log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]");
}
}
return formattedErrorMessage;
}
catch (Exception e) {
String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]";
msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]";
error(false, "got error while formatting errormessage", e);
return errorMessage;
}
}
/**
* retrieve the date and time of the last message.
*/
public String getLastMessageDate() {
String result = "";
if (lastMessageDate != 0)
result = DateUtils.format(new Date(lastMessageDate), DateUtils.FORMAT_FULL_GENERIC);
else
result = "-";
return result;
}
/**
* the MessageKeeper is for keeping the last <code>messageKeeperSize</code>
* messages available, for instance for displaying it in the webcontrol
* @see nl.nn.adapterframework.util.MessageKeeper
*/
public synchronized MessageKeeper getMessageKeeper() {
if (messageKeeper == null)
messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize);
return messageKeeper;
}
public void forEachStatisticsKeeper(StatisticsKeeperIterationHandler hski) {
Object root=hski.start();
forEachStatisticsKeeperBody(hski,root);
hski.end(root);
}
public void forEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object data) {
Object adapterData=hski.openGroup(data,getName(),"adapter");
hski.handleScalar(adapterData,"name", getName());
hski.handleScalar(adapterData,"upSince", getStatsUpSince());
hski.handleScalar(adapterData,"lastMessageDate", getLastMessageDate());
hski.handleScalar(adapterData,"messagesInProcess", getNumOfMessagesInProcess());
hski.handleScalar(adapterData,"messagesProcessed", getNumOfMessagesProcessed());
hski.handleScalar(adapterData,"messagesInError", getNumOfMessagesInError());
hski.handleStatisticsKeeper(adapterData, statsMessageProcessingDuration);
Object recsData=hski.openGroup(adapterData,getName(),"receivers");
Iterator recIt=getReceiverIterator();
if (recIt.hasNext()) {
while (recIt.hasNext()) {
IReceiver receiver=(IReceiver) recIt.next();
Object recData=hski.openGroup(recsData,receiver.getName(),"receiver");
hski.handleScalar(recData,"messagesReceived", receiver.getMessagesReceived());
if (receiver instanceof IReceiverStatistics) {
IReceiverStatistics statReceiver = (IReceiverStatistics)receiver;
Iterator statsIter;
statsIter = statReceiver.getProcessStatisticsIterator();
Object pstatData=hski.openGroup(recData,receiver.getName(),"procStats");
if (statsIter != null) {
while(statsIter.hasNext()) {
StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next();
hski.handleStatisticsKeeper(pstatData,pstat);
}
}
hski.closeGroup(pstatData);
statsIter = statReceiver.getIdleStatisticsIterator();
Object istatData=hski.openGroup(recData,receiver.getName(),"idleStats");
if (statsIter != null) {
while(statsIter.hasNext()) {
StatisticsKeeper pstat = (StatisticsKeeper) statsIter.next();
hski.handleStatisticsKeeper(istatData,pstat);
}
}
hski.closeGroup(istatData);
}
hski.closeGroup(recData);
}
}
hski.closeGroup(recsData);
Object pipelineData=hski.openGroup(adapterData,getName(),"pipeline");
Hashtable pipelineStatistics = getPipeLineStatistics();
// sort the Hashtable
SortedSet sortedKeys = new TreeSet(pipelineStatistics.keySet());
Iterator pipelineStatisticsIter = sortedKeys.iterator();
Object pipestatData=hski.openGroup(pipelineData,getName(),"pipeStats");
while (pipelineStatisticsIter.hasNext()) {
String pipeName = (String) pipelineStatisticsIter.next();
StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName);
hski.handleStatisticsKeeper(pipestatData,pstat);
IPipe pipe = pipeline.getPipe(pipeName);
if (pipe instanceof HasStatistics) {
((HasStatistics) pipe).iterateOverStatistics(hski, pipestatData);
}
}
hski.closeGroup(pipestatData);
pipestatData=hski.openGroup(pipelineData,getName(),"idleStats");
pipelineStatistics = getWaitingStatistics();
if (pipelineStatistics.size()>0) {
// sort the Hashtable
sortedKeys = new TreeSet(pipelineStatistics.keySet());
pipelineStatisticsIter = sortedKeys.iterator();
while (pipelineStatisticsIter.hasNext()) {
String pipeName = (String) pipelineStatisticsIter.next();
StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName);
hski.handleStatisticsKeeper(pipestatData,pstat);
}
}
hski.closeGroup(pipestatData);
hski.closeGroup(pipelineData);
hski.closeGroup(adapterData);
}
/**
* the functional name of this adapter
* @return the name of the adapter
*/
public String getName() {
return name;
}
/**
* The number of messages for which processing ended unsuccessfully.
*/
public long getNumOfMessagesInError() {
synchronized (statsMessageProcessingDuration) {
return numOfMessagesInError;
}
}
public int getNumOfMessagesInProcess() {
synchronized (statsMessageProcessingDuration) {
return numOfMessagesInProcess;
}
}
/**
* Total of messages processed
* @return long total messages processed
*/
public long getNumOfMessagesProcessed() {
synchronized (statsMessageProcessingDuration) {
return numOfMessagesProcessed;
}
}
public Hashtable getPipeLineStatistics() {
return pipeline.getPipeStatistics();
}
public IReceiver getReceiverByName(String receiverName) {
Iterator it = receivers.iterator();
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
if (receiver.getName().equalsIgnoreCase(receiverName)) {
return receiver;
}
}
return null;
}
public Iterator getReceiverIterator() {
return receivers.iterator();
}
public PipeLine getPipeLine() {
return pipeline;
}
public RunStateEnum getRunState() {
return runState.getRunState();
}
public String getRunStateAsString() {
return runState.getRunState().toString();
}
/**
* Return the total processing duration as a StatisticsKeeper
* @see nl.nn.adapterframework.util.StatisticsKeeper
* @return nl.nn.adapterframework.util.StatisticsKeeper
*/
public StatisticsKeeper getStatsMessageProcessingDuration() {
return statsMessageProcessingDuration;
}
public String getStatsUpSince() {
return DateUtils.format(new Date(statsUpSince), DateUtils.FORMAT_FULL_GENERIC);
}
/**
* Retrieve the waiting statistics as a <code>Hashtable</code>
*/
public Hashtable getWaitingStatistics() {
return pipeline.getPipeWaitingStatistics();
}
/**
*
* Process the receiving of a message
* After all Pipes have been run in the PipeLineProcessor, the Object.toString() function
* is called. The result is returned to the Receiver.
*
*/
public PipeLineResult processMessage(String messageId, String message) {
return processMessage(messageId, message, null);
}
public PipeLineResult processMessage(String messageId, String message, PipeLineSession pipeLineSession) {
long startTime = System.currentTimeMillis();
try {
return processMessageWithExceptions(messageId, message, pipeLineSession);
} catch (Throwable t) {
PipeLineResult result = new PipeLineResult();
result.setState(getErrorState());
String msg = "Illegal exception ["+t.getClass().getName()+"]";
INamedObject objectInError = null;
if (t instanceof ListenerException) {
Throwable cause = ((ListenerException) t).getCause();
if (cause instanceof PipeRunException) {
PipeRunException pre = (PipeRunException) cause;
msg = "error during pipeline processing";
objectInError = pre.getPipeInError();
} else if (cause instanceof ManagedStateException) {
msg = "illegal state";
objectInError = this;
}
}
result.setResult(formatErrorMessage(msg, t, message, messageId, objectInError, startTime));
if (isRequestReplyLogging()) {
log.info("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine");
} else {
if (log.isDebugEnabled()) {
log.debug("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine");
}
}
return result;
}
}
public PipeLineResult processMessageWithExceptions(String messageId, String message, PipeLineSession pipeLineSession) throws ListenerException {
PipeLineResult result = new PipeLineResult();
long startTime = System.currentTimeMillis();
// prevent executing a stopped adapter
// the receivers should implement this, but you never now....
RunStateEnum currentRunState = getRunState();
if (!currentRunState.equals(RunStateEnum.STARTED) && !currentRunState.equals(RunStateEnum.STOPPING)) {
String msgAdapterNotOpen =
"Adapter [" + getName() + "] in state [" + currentRunState + "], cannot process message";
throw new ListenerException(new ManagedStateException(msgAdapterNotOpen));
}
incNumOfMessagesInProcess(startTime);
String lastNDC=NDC.peek();
String newNDC="cid [" + messageId + "]";
boolean ndcChanged=!newNDC.equals(lastNDC);
if (ndcChanged) {
NDC.push(newNDC);
}
if (isRequestReplyLogging()) {
if (log.isInfoEnabled()) log.info("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]");
} else {
if (log.isDebugEnabled()) {
log.debug("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]");
} else {
log.info("Adapter [" + name + "] received message with messageId [" + messageId + "]");
}
}
try {
result = pipeline.process(messageId, message,pipeLineSession);
if (isRequestReplyLogging()) {
log.info("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine");
} else {
if (log.isDebugEnabled()) {
log.debug("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine");
}
}
return result;
} catch (Throwable t) {
ListenerException e;
if (t instanceof ListenerException) {
e = (ListenerException) t;
} else {
e = new ListenerException(t);
}
incNumOfMessagesInError();
error(false, "error processing message with messageId [" + messageId+"]: ",e);
throw e;
} finally {
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
//reset the InProcess fields, and increase processedMessagesCount
decNumOfMessagesInProcess(duration);
if (log.isDebugEnabled()) { // for performance reasons
log.debug("Adapter: [" + getName()
+ "] STAT: Finished processing message with messageId [" + messageId
+ "] exit-state [" + result.getState()
+ "] started " + DateUtils.format(new Date(startTime), DateUtils.FORMAT_FULL_GENERIC)
+ " finished " + DateUtils.format(new Date(endTime), DateUtils.FORMAT_FULL_GENERIC)
+ " total duration: " + duration + " msecs");
} else {
log.info("Adapter [" + getName() + "] completed message with messageId [" + messageId + "] with exit-state [" + result.getState() + "]");
}
if (ndcChanged) {
NDC.pop();
}
}
}
/**
* Register a PipeLine at this adapter. On registering, the adapter performs
* a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes.
* @param pipeline
* @throws ConfigurationException
* @see PipeLine
*/
public void registerPipeLine(PipeLine pipeline) throws ConfigurationException {
this.pipeline = pipeline;
pipeline.setAdapter(this);
log.debug("Adapter [" + name + "] registered pipeline [" + pipeline.toString() + "]");
}
/**
* Register a receiver for this Adapter
* @param receiver
* @see IReceiver
*/
public void registerReceiver(IReceiver receiver) {
boolean receiverActive=true;
if (receiver instanceof ReceiverBase) {
receiverActive=((ReceiverBase)receiver).isActive();
}
if (receiverActive) {
receivers.add(receiver);
log.debug("Adapter [" + name + "] registered receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]");
} else {
log.debug("Adapter [" + name + "] did not register inactive receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]");
}
}
/**
* some functional description of the <code>Adapter</code>/
*/
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
/**
* Register a <code>ErrorMessageFormatter</code> as the formatter
* for this <code>adapter</code>
* @param errorMessageFormatter
* @see IErrorMessageFormatter
*/
public void setErrorMessageFormatter(IErrorMessageFormatter errorMessageFormatter) {
this.errorMessageFormatter = errorMessageFormatter;
}
/**
* state to put in PipeLineResult when a PipeRunException occurs
* @param newErrorState java.lang.String
* @see PipeLineResult
*/
public void setErrorState(java.lang.String newErrorState) {
errorState = newErrorState;
}
/**
* state to put in PipeLineResult when a PipeRunException occurs.
*/
public String getErrorState() {
return errorState;
}
/**
* Set the number of messages that are kept on the screen.
* @param size
* @see nl.nn.adapterframework.util.MessageKeeper
*/
public void setMessageKeeperSize(int size) {
this.messageKeeperSize = size;
}
/**
* the functional name of this adapter
*/
public void setName(String name) {
this.name = name;
}
/**
* Start the adapter. The thread-name will be set tot the adapter's name.
* The run method, called by t.start(), will call the startRunning method
* of the IReceiver. The Adapter will be a new thread, as this interface
* extends the <code>Runnable</code> interface. The actual starting is done
* in the <code>run</code> method.
* @see IReceiver#startRunning()
* @see Adapter#run
*/
public void startRunning() {
taskExecutor.execute(new Runnable() {
public void run() {
Thread.currentThread().setName("starting Adapter "+getName());
try {
if (!configurationSucceeded) {
log.error(
"configuration of adapter ["
+ getName()
+ "] did not succeed, therefore starting the adapter is not possible");
warn("configuration did not succeed. Starting the adapter is not possible");
runState.setRunState(RunStateEnum.ERROR);
return;
}
synchronized (runState) {
RunStateEnum currentRunState = getRunState();
if (!currentRunState.equals(RunStateEnum.STOPPED)) {
String msg =
"currently in state [" + currentRunState + "], ignoring start() command";
warn(msg);
return;
}
// start the pipeline
runState.setRunState(RunStateEnum.STARTING);
}
try {
log.debug("Adapter [" + getName() + "] is starting pipeline");
pipeline.start();
}
catch (PipeStartException pre) {
error(true, "got error starting PipeLine", pre);
runState.setRunState(RunStateEnum.ERROR);
return;
}
// as from version 3.0 the adapter is started,
// regardless of receivers are correctly started.
runState.setRunState(RunStateEnum.STARTED);
getMessageKeeper().add("Adapter up and running");
log.info("Adapter [" + getName() + "] up and running");
// starting receivers
Iterator it = receivers.iterator();
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
if (receiver.getRunState() != RunStateEnum.ERROR) {
log.info("Adapter [" + getName() + "] is starting receiver [" + receiver.getName() + "]");
receiver.startRunning();
}
else
log.warn("Adapter [" + getName() + "] will NOT start receiver [" + receiver.getName() + "] as it is in state ERROR");
} //while
// // wait until the stopRunning is called
// waitForRunState(RunStateEnum.STOPPING);
}
catch (Throwable t) {
error(true, "got error starting Adapter", t);
log.error("error running adapter [" + getName() + "]", t);
runState.setRunState(RunStateEnum.ERROR);
}
} // End Runnable.run()
}); // End Runnable
} // End startRunning()
/**
* Stop the <code>Adapter</code> and close all elements like receivers,
* Pipeline, pipes etc.
* The adapter
* will call the <code>IReceiver</code> to <code>stopListening</code>
* <p>Also the <code>PipeLine.close()</code> method will be called,
* closing alle registered pipes. </p>
* @see IReceiver#stopRunning
* @see PipeLine#stop
*/
public void stopRunning() {
synchronized (runState) {
RunStateEnum currentRunState = getRunState();
if (!currentRunState.equals(RunStateEnum.STARTED) && (!currentRunState.equals(RunStateEnum.ERROR))) {
warn("in state [" + currentRunState + "] while stopAdapter() command is issued, ignoring command");
return;
}
if (currentRunState.equals(RunStateEnum.ERROR)) {
runState.setRunState(RunStateEnum.STOPPED);
return;
}
runState.setRunState(RunStateEnum.STOPPING);
}
taskExecutor.execute(new Runnable() {
public void run() {
Thread.currentThread().setName("stopping Adapter " +getName());
try {
log.debug("Adapter [" + name + "] is stopping receivers");
Iterator it = receivers.iterator();
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
try {
receiver.stopRunning();
log.info("Adapter [" + name + "] successfully stopped receiver [" + receiver.getName() + "]");
}
catch (Exception e) {
error(false, "received error while stopping receiver [" + receiver.getName() + "], ignoring this, so watch out.", e);
}
}
// stop the adapter
log.debug("***stopping adapter");
it = receivers.iterator();
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
receiver.waitForRunState(RunStateEnum.STOPPED);
log.info("Adapter [" + getName() + "] stopped [" + receiver.getName() + "]");
}
int currentNumOfMessagesInProcess = getNumOfMessagesInProcess();
if (currentNumOfMessagesInProcess > 0) {
String msg =
"Adapter ["
+ name
+ "] is being stopped while still processing "
+ currentNumOfMessagesInProcess
+ " messages, waiting for them to finish";
warn(msg);
}
waitForNoMessagesInProcess();
log.debug("Adapter [" + name + "] is stopping pipeline");
pipeline.stop();
runState.setRunState(RunStateEnum.STOPPED);
getMessageKeeper().add("Adapter stopped");
} catch (Throwable e) {
log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e);
runState.setRunState(RunStateEnum.ERROR);
}
} // End of run()
}); // End of Runnable
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[name=" + name + "]");
sb.append("[version=" + version + "]");
sb.append("[targetDesignDocument=" + targetDesignDocument + "]");
Iterator it = receivers.iterator();
sb.append("[receivers=");
while (it.hasNext()) {
IReceiver receiver = (IReceiver) it.next();
sb.append(" " + receiver.getName());
}
sb.append("]");
sb.append(
"[pipeLine="
+ ((pipeline != null) ? pipeline.toString() : "none registered")
+ "]"
+ "[started="
+ getRunState()
+ "]");
return sb.toString();
}
public void waitForNoMessagesInProcess() throws InterruptedException {
synchronized (statsMessageProcessingDuration) {
while (getNumOfMessagesInProcess() > 0) {
wait();
}
}
}
public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException {
runState.waitForRunState(requestedRunState);
}
public boolean waitForRunState(RunStateEnum requestedRunState, long maxWait) throws InterruptedException {
return runState.waitForRunState(requestedRunState, maxWait);
}
/**
* AutoStart indicates that the adapter should be started when the configuration
* is started. AutoStart defaults to <code>true</code>
* @since 4.1.1
*/
public void setAutoStart(boolean autoStart) {
this.autoStart = autoStart;
}
public boolean isAutoStart() {
return autoStart;
}
public void setRequestReplyLogging(boolean requestReplyLogging) {
this.requestReplyLogging = requestReplyLogging;
}
public boolean isRequestReplyLogging() {
return requestReplyLogging;
}
public void setActive(boolean b) {
active = b;
}
public boolean isActive() {
return active;
}
public void setTargetDesignDocument(String string) {
targetDesignDocument = string;
}
public String getTargetDesignDocument() {
return targetDesignDocument;
}
public void setTaskExecutor(TaskExecutor executor) {
taskExecutor = executor;
}
public TaskExecutor getTaskExecutor() {
return taskExecutor;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.NamedBean#getBeanName()
*/
public String getBeanName() {
return name;
}
}
|
package com.parc.ccn.data.security;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.KeyParameter;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.util.CCNEncodableObject;
import com.parc.ccn.data.util.GenericXMLEncodable;
import com.parc.ccn.data.util.XMLDecoder;
import com.parc.ccn.data.util.XMLEncodable;
import com.parc.ccn.data.util.XMLEncoder;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.crypto.jce.AESWrapWithPad;
import com.parc.ccn.security.crypto.jce.AESWrapWithPadEngine;
public class WrappedKey extends GenericXMLEncodable implements XMLEncodable {
protected static final String WRAPPED_KEY_ELEMENT = "WrappedKey";
protected static final String WRAPPING_KEY_IDENTIFIER_ELEMENT = "WrappingKeyIdentifier";
protected static final String WRAPPING_KEY_NAME_ELEMENT = "WrappingKeyName";
protected static final String WRAP_ALGORITHM_ELEMENT = "WrapAlgorithm";
protected static final String KEY_ALGORITHM_ELEMENT = "KeyAlgorithm";
protected static final String LABEL_ELEMENT = "Label";
protected static final String ENCRYPTED_NONCE_KEY_ELEMENT = "EncryptedNonceKey";
protected static final String ENCRYPTED_KEY_ELEMENT = "EncryptedKey";
protected static final String NONCE_KEY_ALGORITHM = "AES";
protected static final int NONCE_KEY_LENGTH = 128;
public class WrappingKeyName extends ContentName {
public WrappingKeyName(ContentName name) {
super(name);
}
public WrappingKeyName() {}
@Override
public String contentNameElement() {
return WRAPPING_KEY_NAME_ELEMENT;
}
}
public static class WrappedKeyObject extends CCNEncodableObject<WrappedKey> {
public WrappedKeyObject() throws ConfigurationException, IOException {
super(WrappedKey.class);
}
public WrappedKeyObject(ContentName name, CCNLibrary library) throws XMLStreamException, IOException {
super(WrappedKey.class, name, library);
}
public WrappedKeyObject(ContentName name) throws XMLStreamException, IOException, ConfigurationException {
super(WrappedKey.class, name);
}
public WrappedKeyObject(ContentName name, WrappedKey wrappedKey, CCNLibrary library) {
super(WrappedKey.class, name, wrappedKey, library);
}
public WrappedKeyObject(ContentName name, WrappedKey wrappedKey) throws ConfigurationException, IOException {
super(WrappedKey.class, name, wrappedKey);
}
public WrappedKeyObject(ContentObject block, CCNLibrary library) throws XMLStreamException, IOException {
super(WrappedKey.class, block, library);
}
public WrappedKey wrappedKey() { return data(); }
}
private static final Map<String,String> _WrapAlgorithmMap = new HashMap<String,String>();
byte [] _wrappingKeyIdentifier;
WrappingKeyName _wrappingKeyName;
String _wrapAlgorithm;
String _keyAlgorithm;
String _label;
byte [] _encryptedNonceKey;
byte [] _encryptedKey;
static {
// In Java 1.5, many of these require BouncyCastle. They are typically built in in 1.6.
_WrapAlgorithmMap.put("AES", "AESWRAPWITHPAD");
_WrapAlgorithmMap.put("RSA", "RSA/NONE/OAEPWithSHA256AndMGF1Padding");
}
/**
* Factory methods to build wrapped keys out of their components, wrapping
* in the process. For the moment, these use only the default wrapping algorithms.
*/
public static WrappedKey wrapKey(Key keyToBeWrapped,
String keyAlgorithm,
String keyLabel,
Key wrappingKey)
throws InvalidKeyException {
String wrappingAlgorithm = wrapAlgorithmForKey(wrappingKey.getAlgorithm());
byte [] wrappedNonceKey = null;
byte [] wrappedKey = null;
if (wrappingAlgorithm.equalsIgnoreCase("AESWrapWithPad")) {
byte [] encodedKeyToBeWrapped = keyToBeWrapped.getEncoded();
wrappedKey = AESWrapWithPad(wrappingKey, encodedKeyToBeWrapped, 0, encodedKeyToBeWrapped.length);
} else {
Cipher wrapCipher = null;
try {
wrapCipher = Cipher.getInstance(wrappingAlgorithm);
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm.");
throw new InvalidKeyException("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm.");
} catch (NoSuchPaddingException e) {
Library.logger().warning("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm.");
throw new InvalidKeyException("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm");
}
wrapCipher.init(Cipher.WRAP_MODE, wrappingKey);
// If we are dealing with a short-block cipher, like RSA, we need to
// interpose a nonce key.
Key nonceKey = null;
try {
int wrappedKeyType = getCipherType(keyToBeWrapped.getAlgorithm());
// If we're wrapping a private key in a public key, need to handle multi-block
// keys. Probably don't want to do that with ECB mode. ECIES already acts
// as a hybrid cipher, so we don't need to do this for that.
if (((Cipher.PRIVATE_KEY == wrappedKeyType) || (Cipher.PUBLIC_KEY == wrappedKeyType)) &&
(wrappingKey instanceof PublicKey) && (!wrappingKey.getAlgorithm().equals("ECIES"))) {
nonceKey = generateNonceKey();
//try {
// We know the nonce key is an AES key. Use standard wrap algorithm.
// DKS -- fix when have provider.
//Cipher nonceCipher = Cipher.getInstance(wrapAlgorithmForKey(nonceKey.getAlgorithm()));
//nonceCipher.init(Cipher.WRAP_MODE, nonceKey);
//wrappedKey = nonceCipher.wrap(keyToBeWrapped);
byte [] encodedKeyToBeWrapped = keyToBeWrapped.getEncoded();
wrappedKey = AESWrapWithPad(nonceKey, encodedKeyToBeWrapped, 0, encodedKeyToBeWrapped.length);
//} catch (NoSuchAlgorithmException nsex) {
// Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
// Library.warningStackTrace(nsex);
// throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
wrappedNonceKey = wrapCipher.wrap(nonceKey);
} else {
wrappedKey = wrapCipher.wrap(keyToBeWrapped);
}
} catch (IllegalBlockSizeException ex) {
Library.logger().warning("IllegalBlockSizeException " + ex.getMessage() + " in wrap key -- unexpected, we should have compensated for this. Key to be wrapped algorithm? " + keyToBeWrapped.getAlgorithm() + ". Using nonce key? " + (null == nonceKey));
throw new InvalidKeyException("IllegalBlockSizeException " + ex.getMessage() + " in wrap key -- unexpected, we should have compensated for this. Key to be wrapped algorithm? " + keyToBeWrapped.getAlgorithm() + ". Using nonce key? " + (null == nonceKey));
}
}
// Default wrapping algorithm is being used, don't need to include it.
return new WrappedKey(null, null,
((null == keyAlgorithm) ? keyToBeWrapped.getAlgorithm() : keyAlgorithm),
keyLabel, wrappedNonceKey, wrappedKey);
}
/**
* For now, we have a very loose definition of default -- the default wrap algorithm
* depends on the type of key being used to wrap; similarly the default key algorithm
* depends on the type of the key being wrapped. We assume that the wrapper and unwrapper
* usually know the type of the wrapping key, and can derive the wrapAlgorithm. The
* keyAlgorithm is more often necessary to determine how to decode the key once unwrapped
* so it is more frequently present. Both are optional.
*
* If the caller specifies values they will be encoded on the wire and decoded on
* the other end; defaults will not currently be enforced automatically. This means
* equals behavior should be watched closely.
* @param wrappingKeyIdentifier
* @param wrapAlgorithm
* @param keyAlgorithm
* @param label
* @param encryptedKey
*/
public WrappedKey(byte [] wrappingKeyIdentifier, String wrapAlgorithm, String keyAlgorithm,
String label, byte [] encryptedKey) {
this(wrappingKeyIdentifier, wrapAlgorithm, keyAlgorithm, label, null, encryptedKey);
}
public WrappedKey(byte [] wrappingKeyIdentifier, String wrapAlgorithm, String keyAlgorithm,
String label, byte [] encryptedNonceKey, byte [] encryptedKey) {
_wrappingKeyIdentifier = wrappingKeyIdentifier;
_wrapAlgorithm = wrapAlgorithm;
_keyAlgorithm = keyAlgorithm;
_label = label;
_encryptedNonceKey = encryptedNonceKey;
_encryptedKey = encryptedKey;
}
public WrappedKey(byte [] wrappingKeyIdentifier, byte [] encryptedKey) {
this(wrappingKeyIdentifier, null, null, null, null, encryptedKey);
}
public WrappedKey(byte [] wrappingKeyIdentifier, String label, byte [] encryptedKey) {
this(wrappingKeyIdentifier, null, null, label, null, encryptedKey);
}
/**
* Empty constructor for decoding.
*/
public WrappedKey() {
}
public Key unwrapKey(Key unwrapKey) throws InvalidKeyException, InvalidCipherTextException {
if (null == keyAlgorithm()) {
throw new InvalidCipherTextException("No algorithm specified for key to be unwrapped!");
}
try {
return unwrapKey(unwrapKey, keyAlgorithm());
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to unwrap key with specified algorithm : " + keyAlgorithm());
throw new InvalidCipherTextException("Unexpected NoSuchAlgorithmException attempting to unwrap key with specified algorithm : " + keyAlgorithm());
}
}
public Key unwrapKey(Key unwrapKey, String wrappedKeyAlgorithm) throws InvalidKeyException, NoSuchAlgorithmException, InvalidCipherTextException {
Key unwrappedKey = null;
Library.logger().info("wrap algorithm: " + wrapAlgorithm() + " wa for key " +
wrapAlgorithmForKey(unwrapKey.getAlgorithm()));
if (((null != wrapAlgorithm()) && (wrapAlgorithm().equalsIgnoreCase("AESWrapWithPad"))) ||
wrapAlgorithmForKey(unwrapKey.getAlgorithm()).equalsIgnoreCase("AESWrapWithPad")) {
unwrappedKey = AESUnwrapWithPad(unwrapKey, wrappedKeyAlgorithm, encryptedKey(), 0, encryptedKey().length);
} else {
Cipher unwrapCipher = null;
try {
if (null != wrapAlgorithm()) {
unwrapCipher = Cipher.getInstance(wrapAlgorithm());
} else {
unwrapCipher = Cipher.getInstance(wrapAlgorithmForKey(unwrapKey.getAlgorithm()));
}
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm.");
throw new InvalidKeyException("Unexpected NoSuchAlgorithmException attempting to instantiate wrapping algorithm.");
} catch (NoSuchPaddingException e) {
Library.logger().warning("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm.");
throw new InvalidKeyException("Unexpected NoSuchPaddingException attempting to instantiate wrapping algorithm");
}
unwrapCipher.init(Cipher.UNWRAP_MODE, unwrapKey);
int keyType = getCipherType(wrappedKeyAlgorithm);
if (null != encryptedNonceKey()) {
try {
Key nonceKey = unwrapCipher.unwrap(encryptedNonceKey(), NONCE_KEY_ALGORITHM, Cipher.SECRET_KEY);
//Cipher nonceKeyCipher = Cipher.getInstance(wrapAlgorithmForKey(NONCE_KEY_ALGORITHM));
//nonceKeyCipher.init(Cipher.UNWRAP_MODE, nonceKey);
//unwrappedKey = nonceKeyCipher.unwrap(encryptedKey(), wrappedKeyAlgorithm, keyType);
unwrappedKey = AESUnwrapWithPad(nonceKey, wrappedKeyAlgorithm, encryptedKey(), 0, encryptedKey().length);
} catch(NoSuchAlgorithmException nsex) {
Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
Library.warningStackTrace(nsex);
throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
}
} else {
unwrappedKey = unwrapCipher.unwrap(encryptedKey(), wrappedKeyAlgorithm, keyType);
}
}
return unwrappedKey;
}
public byte [] wrappingKeyIdentifier() { return _wrappingKeyIdentifier; }
public void setWrappingKeyIdentifier(byte [] wrappingKeyIdentifier) {
_wrappingKeyIdentifier = wrappingKeyIdentifier;
}
public void setWrappingKeyIdentifier(Key wrappingKey) {
setWrappingKeyIdentifier(wrappingKeyIdentifier(wrappingKey));
}
public static byte [] wrappingKeyIdentifier(Key wrappingKey) {
return CCNDigestHelper.digest(wrappingKey.getEncoded());
}
public ContentName wrappingKeyName() { return _wrappingKeyName; }
public void setWrappingKeyName(ContentName keyName) { _wrappingKeyName = new WrappingKeyName(keyName); }
public String wrapAlgorithm() { return _wrapAlgorithm; }
public String keyAlgorithm() { return _keyAlgorithm; }
public String label() { return _label; }
public byte [] encryptedNonceKey() { return _encryptedNonceKey; }
public byte [] encryptedKey() { return _encryptedKey; }
@Override
public void decode(XMLDecoder decoder) throws XMLStreamException {
decoder.readStartElement(WRAPPED_KEY_ELEMENT);
if (decoder.peekStartElement(WRAPPING_KEY_IDENTIFIER_ELEMENT)) {
_wrappingKeyIdentifier = decoder.readBinaryElement(WRAPPING_KEY_IDENTIFIER_ELEMENT);
}
if (decoder.peekStartElement(WRAPPING_KEY_NAME_ELEMENT)) {
_wrappingKeyName = new WrappingKeyName();
_wrappingKeyName.decode(decoder);
}
if (decoder.peekStartElement(WRAP_ALGORITHM_ELEMENT)) {
_wrapAlgorithm = decoder.readUTF8Element(WRAP_ALGORITHM_ELEMENT);
}
if (decoder.peekStartElement(KEY_ALGORITHM_ELEMENT)) {
_keyAlgorithm = decoder.readUTF8Element(KEY_ALGORITHM_ELEMENT);
}
if (decoder.peekStartElement(LABEL_ELEMENT)) {
_label = decoder.readUTF8Element(LABEL_ELEMENT);
}
if (decoder.peekStartElement(ENCRYPTED_NONCE_KEY_ELEMENT)) {
_encryptedNonceKey = decoder.readBinaryElement(ENCRYPTED_NONCE_KEY_ELEMENT);
}
_encryptedKey = decoder.readBinaryElement(ENCRYPTED_KEY_ELEMENT);
decoder.readEndElement();
}
@Override
public void encode(XMLEncoder encoder) throws XMLStreamException {
if (!validate()) {
throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing.");
}
encoder.writeStartElement(WRAPPED_KEY_ELEMENT);
if (null != wrappingKeyIdentifier()) {
// needs to handle null WKI
encoder.writeElement(WRAPPING_KEY_IDENTIFIER_ELEMENT, wrappingKeyIdentifier());
}
if (null != wrappingKeyName()) {
wrappingKeyName().encode(encoder);
}
if (null != wrapAlgorithm()) {
//String wrapOID = OIDLookup.getCipherOID(wrapAlgorithm());
encoder.writeElement(WRAP_ALGORITHM_ELEMENT, wrapAlgorithm());
}
if (null != keyAlgorithm()) {
//String keyOID = OIDLookup.getCipherOID(keyAlgorithm());
encoder.writeElement(KEY_ALGORITHM_ELEMENT, keyAlgorithm());
}
if (null != label()) {
encoder.writeElement(LABEL_ELEMENT, label());
}
if (null != encryptedNonceKey()) {
encoder.writeElement(ENCRYPTED_NONCE_KEY_ELEMENT, encryptedNonceKey());
}
encoder.writeElement(ENCRYPTED_KEY_ELEMENT, encryptedKey());
encoder.writeEndElement();
}
@Override
public boolean validate() {
// Only mandatory component is the encrypted key.
return ((null != _encryptedKey) && (_encryptedKey.length > 0));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_encryptedKey);
result = prime * result + Arrays.hashCode(_encryptedNonceKey);
result = prime * result
+ ((_keyAlgorithm == null) ? 0 : _keyAlgorithm.hashCode());
result = prime * result + ((_label == null) ? 0 : _label.hashCode());
result = prime * result
+ ((_wrapAlgorithm == null) ? 0 : _wrapAlgorithm.hashCode());
result = prime * result + Arrays.hashCode(_wrappingKeyIdentifier);
result = prime
* result
+ ((_wrappingKeyName == null) ? 0 : _wrappingKeyName.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;
WrappedKey other = (WrappedKey) obj;
if (!Arrays.equals(_encryptedKey, other._encryptedKey))
return false;
if (!Arrays.equals(_encryptedNonceKey, other._encryptedNonceKey))
return false;
if (_keyAlgorithm == null) {
if (other._keyAlgorithm != null)
return false;
} else if (!_keyAlgorithm.equals(other._keyAlgorithm))
return false;
if (_label == null) {
if (other._label != null)
return false;
} else if (!_label.equals(other._label))
return false;
if (_wrapAlgorithm == null) {
if (other._wrapAlgorithm != null)
return false;
} else if (!_wrapAlgorithm.equals(other._wrapAlgorithm))
return false;
if (!Arrays
.equals(_wrappingKeyIdentifier, other._wrappingKeyIdentifier))
return false;
if (_wrappingKeyName == null) {
if (other._wrappingKeyName != null)
return false;
} else if (!_wrappingKeyName.equals(other._wrappingKeyName))
return false;
return true;
}
public static int getCipherType(String cipherAlgorithm) {
if (cipherAlgorithm.equalsIgnoreCase("ECIES") ||
cipherAlgorithm.equalsIgnoreCase("RSA") || cipherAlgorithm.equalsIgnoreCase("ElGamal")) {
return Cipher.PRIVATE_KEY; // right now assume we don't wrap public keys
}
return Cipher.SECRET_KEY;
}
/**
* Convert a given wrapping key algorithm to the default wrap algorithm for
* using that key.
* @param keyAlgorithm
* @return
*/
public static String wrapAlgorithmForKey(String keyAlgorithm) {
String wrapAlgorithm = _WrapAlgorithmMap.get(keyAlgorithm);
if (null == wrapAlgorithm) {
// punt
return keyAlgorithm;
}
return wrapAlgorithm;
}
public static Key generateNonceKey() {
KeyGenerator kg;
try {
kg = KeyGenerator.getInstance(NONCE_KEY_ALGORITHM);
kg.init(NONCE_KEY_LENGTH);
Key nk = kg.generateKey();
return nk;
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
Library.warningStackTrace(e);
throw new RuntimeException("Configuration error: Unknown default nonce key algorithm: " + NONCE_KEY_ALGORITHM);
}
}
/**
* Until we can sign a provider, we need to reach directly in to wrap public keys in AES keys.
* @param input
* @param offset
* @param length
* @return
*/
protected static byte [] AESWrapWithPad(Key wrappingKey, byte[] input, int offset, int length) {
if (wrappingKey.getAlgorithm() != "AES") {
throw new IllegalArgumentException("AES wrap must wrap with with an AES key.");
}
AESWrapWithPadEngine engine = new AESWrapWithPadEngine();
engine.init(true, new KeyParameter(wrappingKey.getEncoded()));
return engine.wrap(input, offset, length);
}
protected static Key AESUnwrapWithPad(Key unwrappingKey, String wrappedKeyAlgorithm,
byte [] input, int offset, int length) throws InvalidCipherTextException, InvalidKeyException {
if (unwrappingKey.getAlgorithm() != "AES") {
throw new IllegalArgumentException("AES wrap must unwrap with with an AES key.");
}
AESWrapWithPad engine = new AESWrapWithPad();
if ((offset != 0) || (length != input.length)) {
byte [] tmpbuf = new byte[length];
System.arraycopy(input, offset, tmpbuf, 0, length);
input = tmpbuf;
}
return engine.unwrap(unwrappingKey, input, wrappedKeyAlgorithm);
}
}
|
package water;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.io.Closeables;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import water.Job.JobState;
import water.deploy.Node;
import water.deploy.NodeVM;
import water.deploy.VM;
import water.fvec.*;
import water.parser.ParseDataset;
import water.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class TestUtil {
private static int _initial_keycnt = 0;
protected static void startCloud(String[] args, int nnodes) {
for( int i = 1; i < nnodes; i++ ) {
Node n = new NodeVM(args);
n.inheritIO();
n.start();
}
H2O.waitForCloudSize(nnodes);
}
@BeforeClass public static void setupCloud() {
H2O.main(new String[] {});
_initial_keycnt = H2O.store_size();
assert Job.all().length == 0; // No outstanding jobs
}
/** Execute this rule before each test to print test name and test class */
@Rule public TestRule logRule = new TestRule() {
@Override public Statement apply(Statement base, Description description) {
Log.info("
Log.info(" * Test class name: " + description.getClassName());
Log.info(" * Test method name: " + description.getMethodName());
Log.info("
return base;
}
};
@AfterClass public static void checkLeakedKeys() {
Job[] jobs = Job.all();
for( Job job : jobs ) {
assert job.state != JobState.RUNNING : ("UNFINISHED JOB: " + job.job_key + " " + job.description + ", end_time = " + job.end_time + ", state=" + job.state ); // No pending job
DKV.remove(job.job_key);
}
DKV.remove(Job.LIST); // Remove all keys
DKV.remove(Log.LOG_KEY);
DKV.write_barrier();
int leaked_keys = H2O.store_size() - _initial_keycnt;
if( leaked_keys > 0 ) {
for( Key k : H2O.localKeySet() ) {
Value value = DKV.get(k);
Object o = value.type() != TypeMap.PRIM_B ? value.get() : "byte[]";
// Ok to leak VectorGroups
if( o instanceof Vec.VectorGroup )
leaked_keys
else
System.err.println("Leaked key: " + k + " = " + o);
}
}
assertTrue("No keys leaked", leaked_keys <= 0);
_initial_keycnt = H2O.store_size();
}
// Stall test until we see at least X members of the Cloud
public static void stall_till_cloudsize(int x) {
stall_till_cloudsize(x, 10000);
}
public static void stall_till_cloudsize(int x, long ms) {
H2O.waitForCloudSize(x, ms);
UKV.put(Job.LIST, new Job.List()); // Jobs.LIST must be part of initial keys
}
public static File find_test_file(String fname) {
// When run from eclipse, the working directory is different.
// Try pointing at another likely place
File file = new File(fname);
if( !file.exists() )
file = new File("target/" + fname);
if( !file.exists() )
file = new File("../" + fname);
if( !file.exists() )
file = new File("../target/" + fname);
if( !file.exists() )
file = null;
return file;
}
public static Key[] load_test_folder(String fname) {
return load_test_folder(find_test_file(fname));
}
public static Key[] load_test_folder(File folder) {
assert folder.isDirectory();
ArrayList<Key> keys = new ArrayList<Key>();
for( File f : folder.listFiles() ) {
if( f.isFile() )
keys.add(load_test_file(f));
}
Key[] res = new Key[keys.size()];
keys.toArray(res);
return res;
}
public static Key load_test_file(String fname, String key) {
return load_test_file(find_test_file(fname), key);
}
public static Key load_test_file(String fname) {
return load_test_file(find_test_file(fname));
}
public static Key load_test_file(File file, String keyname) {
Key key = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
key = ValueArray.readPut(keyname, fis);
} catch( IOException e ) {
Closeables.closeQuietly(fis);
}
if( key == null )
fail("failed load to " + file.getName());
return key;
}
public static Key load_test_file(File file) {
return load_test_file(file, file.getPath());
}
public static Key loadAndParseFile(String keyName, String path) {
Key fkey = load_test_file(path);
Key okey = Key.make(keyName);
ParseDataset.parse(okey, new Key[] { fkey });
return okey;
}
public static Key loadAndParseFolder(String keyName, String path) {
Key[] keys = load_test_folder(path);
Arrays.sort(keys);
Key okey = Key.make(keyName);
ParseDataset.parse(okey, keys);
return okey;
}
public static ValueArray parse_test_key(Key fileKey, Key parsedKey) {
ParseDataset.parse(parsedKey, new Key[] { fileKey });
return DKV.get(parsedKey).get();
}
public static String replaceExtension(String fname, String newExt) {
int i = fname.lastIndexOf('.');
if( i == -1 )
return fname + "." + newExt;
return fname.substring(0, i) + "." + newExt;
}
public static String getHexKeyFromFile(File f) {
return replaceExtension(f.getName(), "hex");
}
public static String getHexKeyFromRawKey(String str) {
if( str.startsWith("hdfs:
str = str.substring(7);
return replaceExtension(str, "hex");
}
// Build a ValueArray from a collection of normal arrays.
// The arrays must be all the same length.
public static ValueArray va_maker(Key key, Object... arys) {
new ValueArray(key,0).delete_and_lock(null);
// Gather basic column info, 1 column per array
ValueArray.Column cols[] = new ValueArray.Column[arys.length];
char off = 0;
int numrows = -1;
for( int i = 0; i < arys.length; i++ ) {
ValueArray.Column col = cols[i] = new ValueArray.Column();
col._name = "C" + Integer.toString(i+1);
col._off = off;
col._scale = 1;
col._min = Double.MAX_VALUE;
col._max = Double.MIN_VALUE;
col._mean = 0.0;
Object ary = arys[i];
if( ary instanceof byte[] ) {
col._size = 1;
col._n = ((byte[]) ary).length;
} else if( ary instanceof float[] ) {
col._size = -4;
col._n = ((float[]) ary).length;
} else if( ary instanceof double[] ) {
col._size = -8;
col._n = ((double[]) ary).length;
} else if( ary instanceof String[] ) {
col._size = 2; // Catagorical: assign size==2
col._n = ((String[]) ary).length;
col._domain = new String[0];
} else if( ary instanceof short[] ) {
// currently using size==2 (shorts) for Enums instead
throw H2O.unimpl();
} else {
throw H2O.unimpl();
}
off += Math.abs(col._size);
if( numrows == -1 )
numrows = (int) col._n;
else
assert numrows == col._n;
}
Futures fs = new Futures();
int rowsize = off;
ValueArray ary = new ValueArray(key, numrows, rowsize, cols);
int row = 0;
for( int chunk = 0; chunk < ary.chunks(); chunk++ ) {
// Compact data into VA format, and compute min/max/mean
int rpc = ary.rpc(chunk);
int limit = row + rpc;
AutoBuffer ab = new AutoBuffer(rpc * rowsize);
for( ; row < limit; row++ ) {
for( int j = 0; j < arys.length; j++ ) {
ValueArray.Column col = cols[j];
double d;
float f;
byte b;
switch( col._size ) {
// @formatter:off
case 1: ab.put1 (b = ((byte [])arys[j])[row]); d = b; break;
case -4: ab.put4f(f = ((float [])arys[j])[row]); d = f; break;
case -8: ab.put8d(d = ((double[])arys[j])[row]); break;
// @formatter:on
case 2: // Categoricals or enums
String s = ((String[]) arys[j])[row];
String[] dom = col._domain;
int k = index(dom, s);
if( k == dom.length ) {
col._domain = dom = Arrays.copyOf(dom, k + 1);
dom[k] = s;
}
ab.put2((short) k);
d = k;
break;
default:
throw H2O.unimpl();
}
if( d > col._max )
col._max = d;
if( d < col._min )
col._min = d;
col._mean += d;
}
}
Key ckey = ary.getChunkKey(chunk);
DKV.put(ckey, new Value(ckey, ab.bufClose()), fs);
}
// Sum to mean
for( ValueArray.Column col : cols )
col._mean /= col._n;
// 2nd pass for sigma. Sum of squared errors, then divide by n and sqrt
for( int i = 0; i < numrows; i++ ) {
for( int j = 0; j < arys.length; j++ ) {
ValueArray.Column col = cols[j];
double d;
switch( col._size ) {
// @formatter:off
case 1: d = ((byte [])arys[j])[i]; break;
case 2: d = index(col._domain,((String[])arys[j])[i]); break;
case -4: d = ((float [])arys[j])[i]; break;
case -8: d = ((double[])arys[j])[i]; break;
default: throw H2O.unimpl();
// @formatter:on
}
col._sigma += (d - col._mean) * (d - col._mean);
}
}
// RSS to sigma
for( ValueArray.Column col : cols )
col._sigma = Math.sqrt(col._sigma / (col._n - 1));
// Write out data & keys
ary.unlock(null);
fs.blockForPending();
return ary;
}
static int index(String[] dom, String s) {
for( int k = 0; k < dom.length; k++ )
if( dom[k].equals(s) )
return k;
return dom.length;
}
// Make a M-dimensional data grid, with N points on each dimension running
// from 0 to N-1. The grid is flattened, so all N^M points are in the same
// ValueArray. Add a final column which is computed by running an expression
// over the other columns, typically this final column is the input to GLM
// which then attempts to recover the expression.
public abstract static class DataExpr {
public abstract double expr(byte[] cols);
}
@SuppressWarnings("cast") public ValueArray va_maker(Key key, int M, int N, DataExpr expr) {
if( N <= 0 || N > 127 || M <= 0 )
throw H2O.unimpl();
long Q = 1;
for( int i = 0; i < M; i++ ) {
Q *= N;
if( (long) (int) Q != Q )
throw H2O.unimpl();
}
byte[][] x = new byte[M][(int) Q];
double[] d = new double[(int) Q];
byte[] bs = new byte[M];
int q = 0;
int idx = M - 1;
d[q++] = expr.expr(bs);
while( idx >= 0 ) {
if( ++bs[idx] >= N ) {
bs[idx
} else {
idx = M - 1;
for( int i = 0; i < M; i++ )
x[i][q] = bs[i];
d[q++] = expr.expr(bs);
}
}
Object[] arys = new Object[M + 1];
for( int i = 0; i < M; i++ )
arys[i] = x[i];
arys[M] = d;
return va_maker(key, arys);
}
// Fluid Vectors
public static Frame parseFromH2OFolder(String path) {
File file = new File(VM.h2oFolder(), path);
return parseFrame(null, file);
}
public static Frame parseFrame(File file) {
return parseFrame(null, file);
}
public static Frame parseFrame(Key okey, String path) {
return parseFrame(okey, find_test_file(path));
}
public static Frame parseFrame(Key okey, File file) {
if( !file.exists() )
throw new RuntimeException("File not found " + file);
if(okey == null)
okey = Key.make(file.getName());
Key fkey = NFSFileVec.make(file);
return ParseDataset2.parse(okey, new Key[] { fkey });
}
public static Vec vec(int...rows) { return vec(null, null, rows); }
public static Vec vec(String[] domain, int ...rows) { return vec(null, domain, rows); }
public static Vec vec(Key k, String[] domain, int ...rows) {
k = (k==null) ? new Vec.VectorGroup().addVec() : k;
Futures fs = new Futures();
AppendableVec avec = new AppendableVec(k);
NewChunk chunk = new NewChunk(avec, 0);
for( int r = 0; r < rows.length; r++ )
chunk.addNum(rows[r]);
chunk.close(0, fs);
Vec vec = avec.close(fs);
fs.blockForPending();
vec._domain = domain;
return vec;
}
public static Frame frame(String name, Vec vec) { return new Frame().add(name, vec); }
public static Frame frame(String[] names, Vec[] vecs) { return new Frame(names, vecs); }
public static Frame frame(String[] names, double[]... rows) {
assert names == null || names.length == rows[0].length;
Futures fs = new Futures();
Vec[] vecs = new Vec[rows[0].length];
Key keys[] = Vec.VectorGroup.VG_LEN1.addVecs(vecs.length);
for( int c = 0; c < vecs.length; c++ ) {
AppendableVec vec = new AppendableVec(keys[c]);
NewChunk chunk = new NewChunk(vec, 0);
for( int r = 0; r < rows.length; r++ )
chunk.addNum(rows[r][c]);
chunk.close(0, fs);
vecs[c] = vec.close(fs);
}
fs.blockForPending();
return new Frame(names, vecs);
}
public static void dumpKeys(String msg) {
System.err.println("-->> Store dump <<--");
System.err.println(" " + msg);
System.err.println(" Keys: " + H2O.store_size());
for ( Key k : H2O.localKeySet()) System.err.println(" * " + k);
System.err.println("
}
public static String[] ar (String ...a) { return a; }
public static long [] ar (long ...a) { return a; }
public static long[][] ar (long[] ...a) { return a; }
public static int [] ari(int ...a) { return a; }
public static int [][] ar (int[] ...a) { return a; }
}
|
package tridiagonalMatrix;
import java.util.Arrays;
public class Matrix {
private float[] diagonalTop;
private float[] diagonalMiddle;
private float[] diagonalBottom;
public Matrix() {
this.diagonalTop = new float[0];
this.diagonalMiddle = new float[0];
this.diagonalBottom = new float[0];
}
public void setDiagonalTop(float[] diagonalTop) {
this.diagonalTop = diagonalTop;
}
public void setDiagonalMiddle(float[] diagonalMiddle) {
this.diagonalMiddle = diagonalMiddle;
}
public void setDiagonalBottom(float[] diagonalBottom) {
this.diagonalBottom = diagonalBottom;
}
public void fillData(String diagonalTop, String diagonalMiddle, String diagonalBottom) {
String[] numbers = diagonalTop.split(" ");
for (int index = 0; index < numbers.length; index++) {
this.diagonalTop = this.addNumber(this.diagonalTop, Float.parseFloat(numbers[index]));
}
numbers = diagonalMiddle.split(" ");
for (int index = 0; index < numbers.length; index++) {
this.diagonalMiddle = this.addNumber(this.diagonalMiddle, Float.parseFloat(numbers[index]));
}
numbers = diagonalBottom.split(" ");
for (int index = 0; index < numbers.length; index++) {
this.diagonalBottom = this.addNumber(this.diagonalBottom, Float.parseFloat(numbers[index]));
}
}
private float[] addNumber(float[] diagonal, float number) {
float[] result = Arrays.copyOf(diagonal, diagonal.length + 1);
result[diagonal.length] = number;
return result;
}
public void print() {
this.print(true);
}
public void print(boolean formatted) {
if (this.validate()) {
if (formatted) {
int n = diagonalMiddle.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
this.printFloat(this.diagonalMiddle[i]);
} else if (i + 1 == j) {
this.printFloat(this.diagonalTop[i]);
} else if (j + 1 == i) {
this.printFloat(this.diagonalBottom[j]);
} else {
this.printFloat(0);
}
System.out.print(" ");
}
System.out.print("\n");
}
} else {
System.out.println("Top diagonal: " + Arrays.toString(this.diagonalTop));
System.out.println("Middle diagonal: " + Arrays.toString(this.diagonalMiddle));
System.out.println("Bottom diagonal: " + Arrays.toString(this.diagonalBottom));
}
} else {
System.out.println("Matrix is empty or filled incorrectly");
}
}
public boolean validate() {
if (0 < this.diagonalTop.length && 0 < this.diagonalMiddle.length && 0 < this.diagonalBottom.length) {
if (this.diagonalTop.length == this.diagonalMiddle.length - 1 && this.diagonalBottom.length == this.diagonalMiddle.length - 1) {
return true;
}
}
return false;
}
private void printFloat(float number) {
System.out.printf("%6.2f", number);
}
public int getSize() {
return this.diagonalMiddle.length;
}
public float get(String diagonal, int row) {
if (row > this.diagonalMiddle.length || (row == this.diagonalMiddle.length && diagonal == "top") || (row == 1 && diagonal == "bottom")) {
return 0;
}
float result;
switch (diagonal) {
case "top":
result = this.diagonalTop[row - 1];
break;
case "middle":
result = this.diagonalMiddle[row - 1];
break;
case "bottom":
result = this.diagonalBottom[row - 2];
break;
default:
result = 0;
}
return result;
}
}
|
package urllistcompare;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
/**
* @author Rocco Barbini (roccobarbi@gmail.com)
*
* This class is tasked with reading the contents of a CSV file into a URLList.
* It can receive the format, otherwise it will prompt the user to receive it.
* It can be set with the presence of headers, thousand and decimal separators, value separator,
* with the column numbers for the page impressions and the url. Otherwise, it prompts the user
* for those values.
* In case this class is used with a GUI, those values should be set in the constructor or with accessor
* functions before the class start reading the file.
*
*/
public class CSVReader {
// true if the reader is set
private boolean set;
// true if there are column headers
private boolean headers;
// separators: 0 if the value is not set
private boolean isTSep;
private char tSep, dSep, vSep;
// index of the url and impressions columns, -1 if the value is not set
private int urlI, impI;
// bom values (needed to interpret and remove the bom at the start of the file, if present)
private enum bom{
UNICODE(new String(new byte[] {(byte) 0xef, (byte) 0xbb, (byte) 0xbf}), 3);
public final String bomString;
public final int bomLength;
private bom(String bomString, int bomLength){
this.bomString = bomString;
this.bomLength = bomLength;
}
}
/**
* Default constructor, the CSVReader instance is not set and can't be used unless all variables are set correctly.
*/
public CSVReader() {
headers = true; // default
isTSep = true; // default, with tSep = 0 it implies that the value is missing
tSep = 0; // default: indicates that the value is missing
dSep = 0; // default: indicates that the value is missing
vSep = 0; // default: indicates that the value is missing
urlI = -1; // default: indicates that the value is missing
impI = -1; // default: indicates that the value is missing
set = false;
}
/**
*
* @return true if the CSVReader instance is set up and can be used, false otherwise
*/
public boolean isSet(){
return set;
}
/*
* Checks and updates the set status of the CSVReader instance.
* It returns true if the CSVReader instance is set up and can be used, false otherwise
*/
private boolean checkSet(){
set = ((!isTSep || tSep != 0) && dSep != 0 && vSep != 0) && urlI > -1 && impI > -1 && urlI != impI;
return set;
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyjc.testing;
import static org.junit.Assert.fail;
import java.io.*;
import wyjc.Main;
public class TestHarness {
private String srcPath; // path to source files
private String outputPath; // path to output files
private String outputExtension; // the extension of output files
/**
* Construct a test harness object.
*
* @param srcPath
* The path to the source files to be tested
* @param outputPath
* The path to the sample output files to compare against.
* @param outputExtension
* The extension of output files
* @param verification
* if true, the verifier is used.
*/
public TestHarness(String srcPath, String outputPath,
String outputExtension) {
this.srcPath = srcPath.replace('/', File.separatorChar);
this.outputPath = outputPath.replace('/', File.separatorChar);
this.outputExtension = outputExtension;
}
/**
* Compile and execute a test case, whilst comparing its output against the
* sample output.
*
* @param name
* Name of the test to run. This must correspond to an executable
* Java file in the srcPath of the same name.
*/
protected void runTest(String name, String... params) {
final String[] args = new String[3 + params.length];
args[0] = "-wp";
args[1] = "lib/wyrt.jar";
for (int i = 0; i != params.length; ++i) {
args[i + 2] = params[i];
}
args[args.length - 1] = srcPath + File.separatorChar + name + ".whiley";
if (new Main().run(args) != 0) {
fail("couldn't compile test!");
} else {
String output = run(srcPath, name, args);
compare(output, outputPath + File.separatorChar + name + "."
+ outputExtension);
}
}
protected void contextFailTest(String name) {
name = srcPath + File.separatorChar + name + ".whiley";
if (compile("-wp", "lib/wyrt.jar",name)) {
fail("Test compiled when it shouldn't have!");
}
}
protected void runtimeFailTest(String name) {
String fullName = srcPath + File.separatorChar + name + ".whiley";
if(compile("-wp", "lib/wyrt.jar",fullName)) {
fail("couldn't compile test!");
} else {
String output = run(srcPath,name,"-wp", "lib/wyrt.jar");
if(output != null) {
fail("test should have failed at runtime!");
}
}
}
private static boolean compile(String... args) {
return new Main().run(args) == 0;
}
private static String run(String path, String name, String... args) {
try {
// We need to have
String classpath = "../../../" + File.pathSeparator + "."
+ File.pathSeparator + "../../../lib/wyrt.jar";
classpath = classpath.replace('/', File.separatorChar);
String tmp = "java -cp " + classpath + " " + name;
Process p = Runtime.getRuntime().exec(tmp, null, new File(path));
StringBuffer syserr = new StringBuffer();
StringBuffer sysout = new StringBuffer();
new StreamGrabber(p.getErrorStream(), syserr);
new StreamGrabber(p.getInputStream(), sysout);
int exitCode = p.waitFor();
System.err.println(syserr);
if (exitCode != 0) {
return null;
} else {
return sysout.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
fail("Problem running compiled test");
}
return null;
}
/**
* Compare the output of executing java on the test case with a reference
* file.
*
* @param output
* This provides the output from executing java on the test case.
* @param referenceFile
* The full path to the reference file. This should use the
* appropriate separator char for the host operating system.
*/
private static void compare(String output, String referenceFile) {
try {
BufferedReader outReader = new BufferedReader(new StringReader(output));
BufferedReader refReader = new BufferedReader(new FileReader(
new File(referenceFile)));
while (refReader.ready() && outReader.ready()) {
String a = refReader.readLine();
String b = outReader.readLine();
if (a.equals(b)) {
continue;
} else {
System.err.println(" > " + a);
System.err.println(" < " + b);
throw new Error("Output doesn't match reference");
}
}
String l1 = outReader.readLine();
String l2 = refReader.readLine();
if (l1 == null && l2 == null) return;
do {
l1 = outReader.readLine();
l2 = refReader.readLine();
if (l1 != null) {
System.err.println(" < " + l1);
} else if (l2 != null) {
System.err.println(" > " + l2);
}
} while(l1 != null && l2 != null);
fail("Files do not match");
} catch (Exception ex) {
ex.printStackTrace();
fail();
}
}
static public class StreamGrabber extends Thread {
private InputStream input;
private StringBuffer buffer;
StreamGrabber(InputStream input,StringBuffer buffer) {
this.input = input;
this.buffer = buffer;
start();
}
public void run() {
try {
int nextChar;
// keep reading!!
while ((nextChar = input.read()) != -1) {
buffer.append((char) nextChar);
}
} catch (IOException ioe) {
}
}
}
}
|
package org.csstudio.sds.components.ui.internal.figureparts;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureUtilities;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Dimension;
/**
* Linear Scale tick labels.
* @author Xihui Chen
*/
public class LinearScaleTickLabels extends Figure {
/** the array of tick label vales */
private ArrayList<Double> tickLabelValues;
/** the array of tick label */
private ArrayList<String> tickLabels;
/** the array of tick label position in pixels */
private ArrayList<Integer> tickLabelPositions;
/** the array of visibility state of tick label */
private ArrayList<Boolean> tickVisibilities;
/** the maximum length of tick labels */
private int tickLabelMaxLength;
/** the maximum height of tick labels */
private int tickLabelMaxHeight;
private int gridStepInPixel;
private LinearScale scale;
/**
* Constructor.
*
* @param linearScale
* the scale
*/
protected LinearScaleTickLabels(LinearScale linearScale) {
this.scale = linearScale;
tickLabelValues = new ArrayList<Double>();
tickLabels = new ArrayList<String>();
tickLabelPositions = new ArrayList<Integer>();
tickVisibilities = new ArrayList<Boolean>();
setFont(this.scale.getFont());
setForegroundColor(this.scale.getForegroundColor());
}
/**
* Updates the tick labels.
*
* @param length
* scale tick length (without margin)
*/
protected void update(int length) {
tickLabelValues.clear();
tickLabels.clear();
tickLabelPositions.clear();
if (scale.isLogScaleEnabled()) {
updateTickLabelForLogScale(length);
}else {
updateTickLabelForLinearScale(length);
}
updateTickVisibility();
updateTickLabelMaxLengthAndHeight();
}
/**
* Updates tick label for log scale.
*
* @param length
* the length of scale
*/
private void updateTickLabelForLogScale(int length) {
double min = scale.getRange().lower;
double max = scale.getRange().upper;
if(min <= 0 || max <= 0)
throw new IllegalArgumentException(
"the range for log scale must be in positive range");
if (min >= max) {
throw new IllegalArgumentException("min must be less than max.");
}
int digitMin = (int) Math.ceil(Math.log10(min));
int digitMax = (int) Math.ceil(Math.log10(max));
final BigDecimal MIN = new BigDecimal(new Double(min).toString());
BigDecimal tickStep = pow(10, digitMin - 1);
BigDecimal firstPosition;
if (MIN.remainder(tickStep).doubleValue() <= 0) {
firstPosition = MIN.subtract(MIN.remainder(tickStep));
} else {
firstPosition = MIN.subtract(MIN.remainder(tickStep)).add(tickStep);
}
//add min
if(MIN.compareTo(firstPosition) == -1 ) {
tickLabelValues.add(min);
if (scale.isDateEnabled()) {
Date date = new Date((long) MIN.doubleValue());
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(MIN.doubleValue()));
}
tickLabelPositions.add(scale.getMargin());
}
for (int i = digitMin; i <= digitMax; i++) {
for (BigDecimal j = firstPosition; j.doubleValue() <= pow(10, i)
.doubleValue(); j = j.add(tickStep)) {
if (j.doubleValue() > max) {
break;
}
if (scale.isDateEnabled()) {
Date date = new Date((long) j.doubleValue());
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(j.doubleValue()));
}
tickLabelValues.add(j.doubleValue());
int tickLabelPosition = (int) ((Math.log10(j.doubleValue()) - Math
.log10(min))
/ (Math.log10(max) - Math.log10(min)) * length)
+ scale.getMargin();
tickLabelPositions.add(tickLabelPosition);
}
tickStep = tickStep.multiply(pow(10, 1));
firstPosition = tickStep.add(pow(10, i));
}
//add max
if(max > tickLabelValues.get(tickLabelValues.size()-1)) {
tickLabelValues.add(max);
if (scale.isDateEnabled()) {
Date date = new Date((long) max);
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(max));
}
tickLabelPositions.add(scale.getMargin() + length);
}
}
/**
* Updates tick label for normal scale.
*
* @param length
* scale tick length (without margin)
*/
private void updateTickLabelForLinearScale(int length) {
double min = scale.getRange().lower;
double max = scale.getRange().upper;
BigDecimal gridStepBigDecimal = getGridStep(length, min, max);
gridStepInPixel = (int) (length * gridStepBigDecimal.doubleValue()/(max - min));
updateTickLabelForLinearScale(length, gridStepBigDecimal);
}
/**
* Updates tick label for normal scale.
*
* @param length
* scale tick length (without margin)
* @param tickStep
* the tick step
*/
private void updateTickLabelForLinearScale(int length, BigDecimal tickStep) {
double min = scale.getRange().lower;
double max = scale.getRange().upper;
final BigDecimal MIN = new BigDecimal(new Double(min).toString());
BigDecimal firstPosition;
//make firstPosition as the right most of min based on tickStep
/* if (min % tickStep <= 0) */
if (MIN.remainder(tickStep).doubleValue() <= 0) {
/* firstPosition = min - min % tickStep */
firstPosition = MIN.subtract(MIN.remainder(tickStep));
} else {
/* firstPosition = min - min % tickStep + tickStep */
firstPosition = MIN.subtract(MIN.remainder(tickStep)).add(tickStep);
}
// the unit time starts from 1:00
if (scale.isDateEnabled()) {
BigDecimal zeroOclock = firstPosition.subtract(new BigDecimal(
new Double(3600000).toString()));
if (MIN.compareTo(zeroOclock) == -1) {
firstPosition = zeroOclock;
}
}
//add min
if(MIN.compareTo(firstPosition) == -1 ) {
tickLabelValues.add(min);
if (scale.isDateEnabled()) {
Date date = new Date((long) MIN.doubleValue());
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(MIN.doubleValue()));
}
tickLabelPositions.add(scale.getMargin());
}
for (BigDecimal b = firstPosition; b.doubleValue() <= max; b = b
.add(tickStep)) {
if (scale.isDateEnabled()) {
Date date = new Date((long) b.doubleValue());
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(b.doubleValue()));
}
tickLabelValues.add(b.doubleValue());
int tickLabelPosition = (int) ((b.doubleValue() - min)
/ (max - min) * length) + scale.getMargin();
//- LINE_WIDTH;
tickLabelPositions.add(tickLabelPosition);
}
//add max
if(max > tickLabelValues.get(tickLabelValues.size()-1)) {
tickLabelValues.add(max);
if (scale.isDateEnabled()) {
Date date = new Date((long) max);
tickLabels.add(scale.format(date));
} else {
tickLabels.add(scale.format(max));
}
tickLabelPositions.add(scale.getMargin() + length);
}
}
/**
* Updates the visibility of tick labels.
*/
private void updateTickVisibility() {
// initialize the array of tick label visibility state
tickVisibilities.clear();
for (int i = 0; i < tickLabelPositions.size(); i++) {
tickVisibilities.add(Boolean.TRUE);
}
if (tickLabelPositions.size() == 0) {
return;
}
// set the tick label visibility
int previousPosition = 0;
String previousLabel = null;
for (int i = 0; i < tickLabelPositions.size(); i++) {
// check if there is enough space to draw tick label
boolean hasSpaceToDraw = true;
if (i != 0) {
hasSpaceToDraw = hasSpaceToDraw(previousPosition,
tickLabelPositions.get(i), previousLabel, tickLabels.get(i));
}
// check if the same tick label is repeated
String currentLabel = tickLabels.get(i);
boolean isRepeatSameTickAndNotEnd = currentLabel.equals(previousLabel) &&
(i!=0 && i!=tickLabelPositions.size()-1);
// check if the tick label value is major
boolean isMajorTickOrEnd = true;
if (scale.isLogScaleEnabled()) {
isMajorTickOrEnd = isMajorTick(tickLabelValues.get(i))
|| i==0 || i==tickLabelPositions.size()-1;
}
if (!hasSpaceToDraw || isRepeatSameTickAndNotEnd || !isMajorTickOrEnd) {
tickVisibilities.set(i, Boolean.FALSE);
} else {
previousPosition = tickLabelPositions.get(i);
previousLabel = currentLabel;
}
}
}
/**
* Checks if the tick label is major (...,0.01,0.1,1,10,100,...).
*
* @param tickValue
* the tick label value
* @return true if the tick label is major
*/
private boolean isMajorTick(double tickValue) {
if (!scale.isLogScaleEnabled()) {
return true;
}
if (Math.log10(tickValue) % 1 == 0) {
return true;
}
return false;
}
/**
* Returns the state indicating if there is a space to draw tick label.
*
* @param previousPosition
* the previously drawn tick label position.
* @param tickLabelPosition
* the tick label position.
* @param previousTickLabel
* the prevoius tick label.
* @param tickLabel
* the tick label text
* @return true if there is a space to draw tick label
*/
private boolean hasSpaceToDraw(int previousPosition, int tickLabelPosition,
String previousTickLabel, String tickLabel) {
Dimension tickLabelSize = FigureUtilities.getTextExtents(tickLabel, scale.getFont());
Dimension previousTickLabelSize = FigureUtilities.getTextExtents(previousTickLabel, scale.getFont());
int interval = tickLabelPosition - previousPosition;
int textLength = (int) (scale.isHorizontal() ? (tickLabelSize.width/2.0 + previousTickLabelSize.width/2.0)
: tickLabelSize.height);
boolean noLapOnPrevoius = interval > textLength;
boolean noLapOnEnd = true;
if(tickLabelPosition != tickLabelPositions.get(tickLabelPositions.size() - 1)){
Dimension endTickLabelSize = FigureUtilities.getTextExtents(
tickLabels.get(tickLabels.size()-1), scale.getFont());
interval = tickLabelPositions.get(tickLabelPositions.size() - 1) - tickLabelPosition;
textLength = (int) (scale.isHorizontal() ? (tickLabelSize.width/2.0 + endTickLabelSize.width/2.0)
: tickLabelSize.height);
noLapOnEnd = interval > textLength;
}
return noLapOnPrevoius && noLapOnEnd;
}
/**
* Gets max length of tick label.
*/
private void updateTickLabelMaxLengthAndHeight() {
int maxLength = 0;
int maxHeight = 0;
for (int i = 0; i < tickLabels.size(); i++) {
if (tickVisibilities.size() > i && tickVisibilities.get(i) == true) {
Dimension p = FigureUtilities.getTextExtents(tickLabels.get(i), scale.getFont());
if (tickLabels.get(0).startsWith("-") && !tickLabels.get(i).startsWith("-")) {
p.width += FigureUtilities.getTextExtents("-", getFont()).width;
}
if (p.width > maxLength) {
maxLength = p.width;
}
if(p.height > maxHeight){
maxHeight = p.height;
}
}
}
tickLabelMaxLength = maxLength;
tickLabelMaxHeight = maxHeight;
}
/**
* Calculates the value of the first argument raised to the power of the
* second argument.
*
* @param base
* the base
* @param expornent
* the exponent
* @return the value <tt>a<sup>b</sup></tt> in <tt>BigDecimal</tt>
*/
private BigDecimal pow(double base, int expornent) {
BigDecimal value;
if (expornent > 0) {
value = new BigDecimal(new Double(base).toString()).pow(expornent);
} else {
value = BigDecimal.ONE.divide(new BigDecimal(new Double(base)
.toString()).pow(-expornent));
}
return value;
}
/**
* Gets the grid step.
*
* @param lengthInPixels
* scale length in pixels
* @param min
* minimum value
* @param max
* maximum value
* @return rounded value.
*/
private BigDecimal getGridStep(int lengthInPixels, double min, double max) {
if((int) scale.getMajorGridStep() != 0) {
return new BigDecimal(scale.getMajorGridStep());
}
if (lengthInPixels <= 0) {
lengthInPixels = 1;
}
if (min >= max) {
if(max == min)
max ++;
else
throw new IllegalArgumentException("min must be less than max.");
}
double length = Math.abs(max - min);
double gridStepHint = length / lengthInPixels
* scale.getMajorTickMarkStepHint();
if(scale.isDateEnabled()) {
//by default, make the least step to be minutes
long timeStep;
if(max - min < 60000) // < 1 min, step = 1 sec
timeStep= 1000l;
else if (max -min < 43200000) // < 12 hour, step = 1 min
timeStep = 60000l;
else if (max - min < 604800000) // < 7 days, step = 1 hour
timeStep = 3600000l;
else
timeStep = 86400000l;
if (scale.getTimeUnit() == Calendar.SECOND) {
timeStep = 1000l;
} else if (scale.getTimeUnit() == Calendar.MINUTE) {
timeStep = 60000l;
}else if (scale.getTimeUnit() == Calendar.HOUR_OF_DAY) {
timeStep = 3600000l;
}else if (scale.getTimeUnit() == Calendar.DATE) {
timeStep = 86400000l;
}else if (scale.getTimeUnit() == Calendar.MONTH) {
timeStep = 30l*86400000l;
}else if (scale.getTimeUnit() == Calendar.YEAR) {
timeStep = 365l*86400000l;
}
double temp = gridStepHint + (timeStep - gridStepHint%timeStep);
return new BigDecimal(temp);
}
// gridStepHint --> mantissa * 10 ** exponent
// e.g. 724.1 --> 7.241 * 10 ** 2
double mantissa = gridStepHint;
int exponent = 0;
if (mantissa < 1) {
while (mantissa < 1) {
mantissa *= 10.0;
exponent
}
} else {
while (mantissa >= 10) {
mantissa /= 10.0;
exponent++;
}
}
// calculate the grid step with hint.
BigDecimal gridStep;
if (mantissa > 7.5) {
// gridStep = 10.0 * 10 ** exponent
gridStep = BigDecimal.TEN.multiply(pow(10, exponent));
} else if (mantissa > 3.5) {
// gridStep = 5.0 * 10 ** exponent
gridStep = new BigDecimal(new Double(5).toString()).multiply(pow(
10, exponent));
} else if (mantissa > 1.5) {
// gridStep = 2.0 * 10 ** exponent
gridStep = new BigDecimal(new Double(2).toString()).multiply(pow(
10, exponent));
} else {
// gridStep = 1.0 * 10 ** exponent
gridStep = pow(10, exponent);
}
return gridStep;
}
/**
* Gets the tick label positions.
*
* @return the tick label positions
*/
public ArrayList<Integer> getTickLabelPositions() {
return tickLabelPositions;
}
@Override
protected void paintClientArea(Graphics graphics) {
graphics.translate(bounds.x, bounds.y);
if (scale.isHorizontal()) {
drawXTick(graphics);
} else {
drawYTick(graphics);
}
super.paintClientArea(graphics);
};
/**
* Draw the X tick.
*
* @param grahics
* the graphics context
*/
private void drawXTick(Graphics grahics) {
// draw tick labels
grahics.setFont(scale.getFont());
for (int i = 0; i < tickLabelPositions.size(); i++) {
if (tickVisibilities.get(i) == true) {
String text = tickLabels.get(i);
int fontWidth = FigureUtilities.getTextExtents(text, getFont()).width;
int x = (int) Math.ceil(tickLabelPositions.get(i) - fontWidth / 2.0);// + offset);
grahics.drawText(text, x, 0);
}
}
}
/**
* Draw the Y tick.
*
* @param grahpics
* the graphics context
*/
private void drawYTick(Graphics grahpics) {
// draw tick labels
grahpics.setFont(scale.getFont());
int fontHeight = tickLabelMaxHeight;
for (int i = 0; i < tickLabelPositions.size(); i++) {
if (tickVisibilities.size() == 0 || tickLabels.size() == 0) {
break;
}
if (tickVisibilities.get(i) == true) {
String text = tickLabels.get(i);
int x = 0;
if (tickLabels.get(0).startsWith("-") && !text.startsWith("-")) {
x += FigureUtilities.getTextExtents("-", getFont()).width;
}
int y = (int) Math.ceil(scale.getLength() - tickLabelPositions.get(i)
- fontHeight / 2.0);
grahpics.drawText(text, x, y);
}
}
}
/**
* @return the tickLabelMaxLength
*/
public int getTickLabelMaxLength() {
return tickLabelMaxLength;
}
/**
* @return the tickLabelMaxHeight
*/
public int getTickLabelMaxHeight() {
return tickLabelMaxHeight;
}
/**
* @return the tickVisibilities
*/
public ArrayList<Boolean> getTickVisibilities() {
return tickVisibilities;
}
/**
* @return the gridStepInPixel
*/
public int getGridStepInPixel() {
return gridStepInPixel;
}
}
|
package com.atlassian.plugin.spring;
import com.atlassian.plugin.osgi.hostcomponents.ContextClassLoaderStrategy;
import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider;
import com.atlassian.plugin.osgi.hostcomponents.HostComponentRegistration;
import com.atlassian.plugin.osgi.hostcomponents.PropertyBuilder;
import com.atlassian.plugin.osgi.hostcomponents.impl.DefaultComponentRegistrar;
import junit.framework.TestCase;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import static com.atlassian.plugin.spring.PluginBeanDefinitionRegistry.HOST_COMPONENT_PROVIDER;
public class TestSpringHostComponentProviderFactoryBeanWithXmlConfiguration extends TestCase
{
private static final HashSet<Class> FOOABLE_BEAN_INTERFACES = new HashSet<Class>(Arrays.asList(Serializable.class, Map.class, Cloneable.class, Fooable.class, Barable.class));
private static final HashSet<Class> FOO_BARABLE_INTERFACES = new HashSet<Class>(Arrays.asList(Fooable.class, Barable.class));
public void testProvide()
{
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test.xml"));
HostComponentProvider provider = getHostProvider(factory);
DefaultComponentRegistrar registrar = new DefaultComponentRegistrar();
provider.provide(registrar);
List<HostComponentRegistration> list = registrar.getRegistry();
assertNotNull(list);
assertEquals(1, list.size());
assertEquals("foo", list.get(0).getProperties().get("bean-name"));
assertEquals(5, list.get(0).getMainInterfaces().length);
assertEquals(FOOABLE_BEAN_INTERFACES, new HashSet<Class>(Arrays.asList(list.get(0).getMainInterfaceClasses())));
assertEquals(ContextClassLoaderStrategy.USE_PLUGIN.name(), list.get(0).getProperties().get(PropertyBuilder.CONTEXT_CLASS_LOADER_STRATEGY));
}
private HostComponentProvider getHostProvider(BeanFactory factory)
{
final HostComponentProvider provider = (HostComponentProvider) factory.getBean(HOST_COMPONENT_PROVIDER);
assertNotNull(provider);
return provider;
}
public void testProvideWithPrototype()
{
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test-prototype.xml"));
HostComponentProvider provider = getHostProvider(factory);
DefaultComponentRegistrar registrar = new DefaultComponentRegistrar();
provider.provide(registrar);
List<HostComponentRegistration> list = registrar.getRegistry();
assertNotNull(list);
assertEquals(1, list.size());
assertEquals("foo", list.get(0).getProperties().get("bean-name"));
assertEquals(5, list.get(0).getMainInterfaces().length);
assertEquals(FOOABLE_BEAN_INTERFACES, new HashSet<Class>(Arrays.asList(list.get(0).getMainInterfaceClasses())));
}
public void testProvideWithCustomInterface()
{
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test-interface.xml"));
HostComponentProvider provider = getHostProvider(factory);
DefaultComponentRegistrar registrar = new DefaultComponentRegistrar();
provider.provide(registrar);
List<HostComponentRegistration> list = registrar.getRegistry();
assertNotNull(list);
assertEquals(2, list.size());
if ("foo".equals(list.get(0).getProperties().get("bean-name")))
{
assertFoo(list.get(0));
assertFooMultipleInterfaces(list.get(1));
}
else
{
assertFoo(list.get(1));
assertFooMultipleInterfaces(list.get(0));
}
}
private void assertFoo(HostComponentRegistration registration)
{
assertEquals("foo", registration.getProperties().get("bean-name"));
assertEquals(1, registration.getMainInterfaces().length);
assertEquals(BeanFactoryAware.class.getName(), registration.getMainInterfaces()[0]);
}
private void assertFooMultipleInterfaces(HostComponentRegistration registration)
{
assertEquals("fooMultipleInterface", registration.getProperties().get("bean-name"));
assertEquals(2, registration.getMainInterfaces().length);
assertEquals(BeanFactoryAware.class.getName(), registration.getMainInterfaces()[0]);
assertEquals(Barable.class.getName(), registration.getMainInterfaces()[1]);
}
public void testProvideWithInterfaceOnSuperClass()
{
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test-super-interface.xml"));
HostComponentProvider provider = getHostProvider(factory);
DefaultComponentRegistrar registrar = new DefaultComponentRegistrar();
provider.provide(registrar);
List<HostComponentRegistration> list = registrar.getRegistry();
assertNotNull(list);
assertEquals(1, list.size());
assertEquals("foobarable", list.get(0).getProperties().get("bean-name"));
assertEquals(2, list.get(0).getMainInterfaces().length);
assertEquals(FOO_BARABLE_INTERFACES, new HashSet<Class>(Arrays.asList(list.get(0).getMainInterfaceClasses())));
}
public void testProvideWithNestedContexts()
{
XmlBeanFactory parentFactory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test.xml"));
XmlBeanFactory childFactory = new XmlBeanFactory(new ClassPathResource("com/atlassian/plugin/spring/pluginns/plugins-spring-test-child.xml"), parentFactory);
HostComponentProvider provider = getHostProvider(childFactory);
assertTrue(parentFactory.containsBeanDefinition(HOST_COMPONENT_PROVIDER));
assertTrue(childFactory.containsBeanDefinition(HOST_COMPONENT_PROVIDER));
DefaultComponentRegistrar registrar = new DefaultComponentRegistrar();
provider.provide(registrar);
List<HostComponentRegistration> list = registrar.getRegistry();
assertNotNull(list);
assertEquals(2, list.size());
}
}
|
package org.camunda.bpm.spring.boot.starter.example.simple;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {SimpleApplication.class})
public class SimpleApplicationTest {
@Rule
public Timeout timeout = Timeout.seconds(5);
@Autowired
private SimpleApplication application;
@Test
public void would_fail_if_process_not_completed_after_5_seconds() throws InterruptedException {
while (!application.contextClosed && !application.isProcessInstanceFinished()) {
Thread.sleep(500L);
}
}
}
|
package de.unistuttgart.quadrama.experiments;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.factory.CollectionReaderFactory.createReaderDescription;
import java.io.IOException;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.pipeline.SimplePipeline;
import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiWriter;
import de.unistuttgart.quadrama.core.SetDramaMetaData;
import de.unistuttgart.quadrama.io.gutenbergde.GutenbergDEReader;
import de.unistuttgart.quadrama.io.tei.textgrid.TextgridTEIReader;
public class CollectDocuments {
public static void main(String[] args) throws UIMAException, IOException {
System.err.println("Collecting Wieland ...");
SimplePipeline.runPipeline(
createReaderDescription(GutenbergDEReader.class,
GutenbergDEReader.PARAM_INPUT_DIRECTORY,
"src/main/resources/raw/Wieland/"),
createEngineDescription(SetDramaMetaData.class,
SetDramaMetaData.PARAM_DRAMAID, "RuJ-Wieland"),
createEngineDescription(XmiWriter.class,
XmiWriter.PARAM_TARGET_LOCATION,
"src/main/resources/romeo-and-juliet/"));
System.err.println("Collecting Schlegel ...");
SimplePipeline.runPipeline(
createReaderDescription(TextgridTEIReader.class,
TextgridTEIReader.PARAM_INPUT_DIRECTORY,
"src/main/resources/raw/Schlegel/"),
createEngineDescription(SetDramaMetaData.class,
SetDramaMetaData.PARAM_DRAMAID, "RuJ-Schlegel"),
createEngineDescription(XmiWriter.class,
XmiWriter.PARAM_TARGET_LOCATION,
"src/main/resources/romeo-and-juliet/"));
System.err.println("Collecting Shakespeare ...");
SimplePipeline.runPipeline(
createReaderDescription(TextgridTEIReader.class,
TextgridTEIReader.PARAM_INPUT_DIRECTORY,
"src/main/resources/raw/Shakespeare/",
TextgridTEIReader.PARAM_LANGUAGE, "en"),
createEngineDescription(SetDramaMetaData.class,
SetDramaMetaData.PARAM_DRAMAID, "RuJ-Shakespeare"),
createEngineDescription(XmiWriter.class,
XmiWriter.PARAM_TARGET_LOCATION,
"src/main/resources/romeo-and-juliet/"));
}
}
|
package edu.cuny.citytech.foreachlooptolambda.ui.refactorings;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.EnhancedForStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.internal.codeassist.ThrownExceptionFinder;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import edu.cuny.citytech.foreachlooptolambda.ui.messages.Messages;
import edu.cuny.citytech.foreachlooptolambda.ui.visitors.EnhancedForStatementVisitor;
import edu.cuny.citytech.refactoring.common.core.Refactoring;
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
public class ForeachLoopToLambdaRefactoring extends Refactoring {
/**
* The methods to refactor.
*/
private Set<IMethod> methods;
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
*/
public ForeachLoopToLambdaRefactoring(IMethod... methods) {
this.methods = new HashSet<IMethod>(Arrays.asList(methods));
}
/**
* Default constructor
*/
public ForeachLoopToLambdaRefactoring() {
}
@Override
public String getName() {
// TODO: Please rename.
return Messages.ForEachLoopToLambdaRefactoring_Name;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
// TODO Empty for now.
final RefactoringStatus status = new RefactoringStatus();
return status;
}
// this method get the EnhancedForSrarement to check the precondition
private static Set<EnhancedForStatement> getEnhancedForStatements(IMethod method, IProgressMonitor pm)
throws JavaModelException {
ICompilationUnit iCompilationUnit = method.getCompilationUnit();
// there may be a shared AST already parsed. Let's try to get that
// one.
CompilationUnit compilationUnit = RefactoringASTParser.parseWithASTProvider(iCompilationUnit, true,
new SubProgressMonitor(pm, 1));
// get the method declaration ASTNode.
MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, compilationUnit);
final Set<EnhancedForStatement> statements = new LinkedHashSet<EnhancedForStatement>();
// extract all enhanced for loop statements in the method.
methodDeclarationNode.accept(new ASTVisitor() {
@Override
public boolean visit(EnhancedForStatement node) {
statements.add(node);
return super.visit(node);
}
});
return statements;
}
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
final RefactoringStatus status = new RefactoringStatus();
for (IMethod method : methods) {
Set<EnhancedForStatement> statements = getEnhancedForStatements(method, new SubProgressMonitor(pm, 1));
IProgressMonitor subMonitor = new SubProgressMonitor(pm, statements.size());
// check preconditions on each.
statements.stream().forEach(s -> status.merge(checkEnhancedForStatement(s, method, subMonitor)));
pm.worked(1);
}
return status;
} finally {
pm.done();
}
}
// Checking if the EnhancedForLoop iterate over collection
private static boolean checkEnhancedForStatementIteratesOverCollection(EnhancedForStatement enhancedForStatement,
IProgressMonitor pm) {
boolean isNotInstanceOfCollection = true;
Expression expression = enhancedForStatement.getExpression();
ITypeBinding nodeBindingType = expression.resolveTypeBinding();
if (nodeBindingType.isArray()) {
isNotInstanceOfCollection = true;
} else {
// STEP 1: getting java the element of the type,
IType iTypeElement = (IType) nodeBindingType.getJavaElement();
// Debug Purpose: will be remove once code is done
System.out.println("This is ITypeElement " + iTypeElement);
try {
// STEP 2: getting java iTypeHeirchay,
ITypeHierarchy iTypeHeirchay = iTypeElement.newSupertypeHierarchy(pm);
// Debug Purpose: will be remove once code is done
System.out.println("this is ITypeHeirchay " + iTypeHeirchay);
// STEP 3:
IType[] superInterface = iTypeHeirchay.getAllInterfaces();
// Debug Purpose: will be remove once code is done
for (IType iType2 : superInterface) {
System.out.println(iType2);
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String typeName = nodeBindingType.getQualifiedName();
System.out.println(" name " + typeName);
// passing the default method by comparing List
if ((typeName.startsWith("java.util.Collection")) || (typeName.startsWith("java.util.List"))) {
isNotInstanceOfCollection = false;
}
return isNotInstanceOfCollection;
}
// getting any uncaught exception
public void checkException() {
ThrownExceptionFinder thrownUncaughtExceptions = new ThrownExceptionFinder();
ReferenceBinding[] thrownUncaughtException = thrownUncaughtExceptions.getThrownUncaughtExceptions();
if (thrownUncaughtException.length > 0) {
}
}
// Checking with the precondiiton,
private static RefactoringStatus checkEnhancedForStatement(EnhancedForStatement enhancedForStatement,
IMethod method, IProgressMonitor pm) {
try {
RefactoringStatus status = new RefactoringStatus();
// create the visitor.
EnhancedForStatementVisitor visitor = new EnhancedForStatementVisitor();
// have the AST node "accept" the visitor.
enhancedForStatement.accept(visitor);
final Set<String> warningStatement = new HashSet<String>();
if (visitor.containsBreak()) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainBreak, method);
}
if (visitor.containsContinue()) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainContinue, method);
}
if (visitor.containsInvalidReturn()) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainInvalidReturn, method);
}
if (visitor.containsMultipleReturn()) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainMultipleReturn, method);
}
if (visitor.containsException()) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainException, method);
}
if (checkEnhancedForStatementIteratesOverCollection(enhancedForStatement, pm)) {
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_IteratesOverCollection, method);
}
// status.merge(checkMethodBody(method, new SubProgressMonitor(pm,
pm.worked(1);
return status; // passed.
} finally {
pm.done();
}
}
protected static RefactoringStatus checkMethodBody(IMethod method, IProgressMonitor pm) {
RefactoringStatus status = new RefactoringStatus();
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = RefactoringASTParser.parseWithASTProvider(root, false, new SubProgressMonitor(pm, 1));
MethodDeclaration declaration;
try {
declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
@SuppressWarnings("rawtypes")
List statements = body.statements();
if (!statements.isEmpty()) {
// TODO for now.
addWarning(status, Messages.ForEachLoopToLambdaRefactoring_NoMethodsWithStatements, method);
}
}
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
}
protected static void addWarning(RefactoringStatus status, String message, IMethod method) {
status.addWarning(MessageFormat.format(message, method.getElementName()), JavaStatusContext.create(method));
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.ForEachLoopToLambdaRefactoring_CreatingChange, 1);
return new NullChange(getName());
} finally {
pm.done();
}
}
}
|
package io.subutai.core.security.rest;
import javax.naming.NamingException;
import javax.ws.rs.core.Response;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import io.subutai.common.security.crypto.pgp.PGPKeyUtil;
import io.subutai.common.security.objects.KeyTrustLevel;
import io.subutai.common.util.JsonUtil;
import io.subutai.common.util.ServiceLocator;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.core.security.api.crypto.KeyManager;
import io.subutai.core.security.api.model.SecurityKey;
import io.subutai.core.security.rest.model.SecurityKeyData;
/**
* Implementation of Key Server Rest
*/
public class SecurityManagerRestImpl implements SecurityManagerRest
{
private static final Logger logger = LoggerFactory.getLogger( SecurityManagerRestImpl.class );
// SecurityManager service
private SecurityManager securityManager;
public SecurityManagerRestImpl( SecurityManager securityManager )
{
this.securityManager = securityManager;
}
@Override
public Response addPublicKeyRing( final String identityId, final String keyText )
{
securityManager.getKeyManager().savePublicKeyRing( identityId, ( short ) 3, keyText );
return Response.ok().build();
}
@Override
public Response removePublicKeyRing( final String identityId )
{
securityManager.getKeyManager().removePublicKeyRing( identityId );
return Response.ok().build();
}
@Override
public Response getPublicKeyRing( final String identityId )
{
String key = "";
try
{
key = securityManager.getKeyManager().getPublicKeyRingAsASCII( identityId );
if ( Strings.isNullOrEmpty( key ) )
{
logger.info( " ************* Public Key not found with id:" + identityId);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( key ).build();
}
}
catch(Exception ex)
{
logger.error( "************ Error in getPublicKeyRest identityId:" + identityId,ex);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
}
@Override
public Response getPublicKey( final String identityId )
{
String key = "";
try
{
key = securityManager.getKeyManager().getPublicKeyRingAsASCII( identityId );
if ( Strings.isNullOrEmpty( key ) )
{
logger.info( " ************* Public Key not found with id:" + identityId);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( key ).build();
}
}
catch(Exception ex)
{
logger.info( " ************* Error ! Public Key not found with id:" + identityId,ex);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
}
@Override
public Response getPublicKeyId( final String identityId )
{
try
{
PGPPublicKeyRing pubRing = securityManager.getKeyManager().getPublicKeyRing( identityId );
PGPPublicKey key = pubRing.getPublicKey();
if ( key == null )
{
logger.info( " ************* Public Key not found with id:" + identityId);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( PGPKeyUtil.encodeNumericKeyId( key.getKeyID() ) ).build();
}
}
catch(Exception ex)
{
logger.info( " ************* Error ! Public Key not found with id:" + identityId,ex);
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
}
@Override
public Response getUserKeyTrustTree()
{
try
{
IdentityManager identityManager = ServiceLocator.getServiceNoCache( IdentityManager.class );
User user = null;
if ( identityManager != null )
{
user = identityManager.getActiveUser();
return getKeyTrustTree( user.getSecurityKeyId() );
}
}
catch ( NamingException e )
{
logger.error( "Error getting identity manager.", e );
}
return null;
}
@Override
public Response getPublicKeyFingerprint( final String identityId )
{
String fingerprint = securityManager.getKeyManager().getFingerprint( identityId );
if ( fingerprint == null )
{
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( fingerprint ).build();
}
}
@Override
public Response getKeyTrustTree( String identityId )
{
try
{
logger.debug( "Received identityId: " + identityId );
KeyManager keyManager = securityManager.getKeyManager();
SecurityKey securityKey = keyManager.getKeyTrustTree( identityId );
return Response.ok( JsonUtil.toJson( securityKey ) ).build();
}
catch ( Exception ex )
{
return Response.serverError().build();
}
}
@Override
public Response revokeKey( String sourceFingerprint, String targetFingerprint )
{
try
{
KeyManager keyManager = securityManager.getKeyManager();
keyManager.setKeyTrust( sourceFingerprint, targetFingerprint, KeyTrustLevel.Never.getId() );
}
catch ( Exception e )
{
return Response.serverError().build();
}
return Response.ok().build();
}
@Override
public Response setTrust( String source, String target, int level )
{
try
{
KeyManager keyManager = securityManager.getKeyManager();
keyManager.setKeyTrust( source, target, level );
}
catch ( Exception e )
{
return Response.serverError().build();
}
return Response.ok().build();
}
@Override
public Response approveKey( String source, String target )
{
try
{
KeyManager keyManager = securityManager.getKeyManager();
keyManager.setKeyTrust( source, target, KeyTrustLevel.Full.getId() );
}
catch ( Exception e )
{
return Response.serverError().build();
}
return Response.ok().build();
}
@Override
public Response signKey( SecurityKeyData keyData )
{
String key = securityManager.getKeyManager()
.signPublicKey( keyData.getSourceKeyIdentityId(), keyData.getKeyText(),
keyData.getTrustlevel() );
if ( Strings.isNullOrEmpty( key ) )
{
return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
}
else
{
return Response.ok( key ).build();
}
}
@Override
public Response verifySignature( String sourceFingerprint, String targetFingerprint )
{
KeyManager keyManager = securityManager.getKeyManager();
boolean certfied = keyManager.verifySignature( sourceFingerprint, targetFingerprint );
return Response.ok( certfied ).build();
}
@Override
public Response verifyTrust( String sourceFingerprint, String targetFingerprint )
{
return null;
}
}
|
package org.opencps.dossiermgt.action.impl;
import com.liferay.document.library.kernel.service.DLAppLocalServiceUtil;
import com.liferay.document.library.kernel.util.DLUtil;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.TimeZoneUtil;
import com.liferay.portal.kernel.util.URLCodec;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.text.similarity.CosineSimilarity;
import org.opencps.auth.utils.APIDateTimeUtils;
import org.opencps.communication.model.ServerConfig;
import org.opencps.communication.service.ServerConfigLocalServiceUtil;
import org.opencps.datamgt.constants.DataMGTConstants;
import org.opencps.datamgt.model.DictCollection;
import org.opencps.datamgt.model.DictItem;
import org.opencps.datamgt.model.DictItemMapping;
import org.opencps.datamgt.service.DictCollectionLocalServiceUtil;
import org.opencps.datamgt.service.DictItemLocalServiceUtil;
import org.opencps.datamgt.service.DictItemMappingLocalServiceUtil;
import org.opencps.dossiermgt.action.DVCQGIntegrationAction;
import org.opencps.dossiermgt.action.DossierActions;
import org.opencps.dossiermgt.action.ServiceInfoActions;
import org.opencps.dossiermgt.action.util.DossierFileUtils;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.opencps.dossiermgt.input.model.DossierInputModel;
import org.opencps.dossiermgt.model.AccessToken;
import org.opencps.dossiermgt.model.ActionConfig;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierAction;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.DossierPart;
import org.opencps.dossiermgt.model.DossierStatusMapping;
import org.opencps.dossiermgt.model.ProcessOption;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.model.ServiceFileTemplate;
import org.opencps.dossiermgt.model.ServiceInfo;
import org.opencps.dossiermgt.model.ServiceInfoMapping;
import org.opencps.dossiermgt.model.impl.ServiceInfoImpl;
import org.opencps.dossiermgt.service.AccessTokenLocalServiceUtil;
import org.opencps.dossiermgt.service.ActionConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.CPSDossierBusinessLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierActionLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierPartLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierStatusMappingLocalServiceUtil;
import org.opencps.dossiermgt.service.ProcessOptionLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceFileTemplateLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceInfoMappingLocalServiceUtil;
import org.opencps.usermgt.model.Answer;
import org.opencps.usermgt.model.Applicant;
import org.opencps.usermgt.model.Question;
import org.opencps.usermgt.service.AnswerLocalServiceUtil;
import org.opencps.usermgt.service.ApplicantLocalServiceUtil;
import org.opencps.usermgt.service.QuestionLocalServiceUtil;
import org.opencps.usermgt.service.util.DateTimeUtils;
import backend.auth.api.exception.ErrorMsgModel;
/**
* @author trungnt
*
*/
public class DVCQGIntegrationActionImpl implements DVCQGIntegrationAction {
private static HashMap<String, Map<CharSequence, Integer>> _serviceInfoMapChars = new HashMap<String, Map<CharSequence, Integer>>();;
private static HashMap<String, JSONObject> _serviceInfoMapItems = new HashMap<String, JSONObject>();
private static HashMap<String, Map<CharSequence, Integer>> _dictItemMapChars = new HashMap<String, Map<CharSequence, Integer>>();;
private static HashMap<String, JSONObject> _dictItemMapItems = new HashMap<String, JSONObject>();
private static JSONArray _serviceInfoDVCQG = JSONFactoryUtil.createJSONArray();
private Log _log = LogFactoryUtil.getLog(DVCQGIntegrationActionImpl.class);
private static final String LUCENE_DATE_FORMAT = "yyyyMMddHHmmss";
private static final String HCM_TIMEZONE = "Asia/Ho_Chi_Minh";
private String convertDate2String(Date date) {
DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(LUCENE_DATE_FORMAT);
if (Validator.isNull(date)) {
return StringPool.BLANK;
}
dateFormat.setTimeZone(TimeZoneUtil.getTimeZone(HCM_TIMEZONE));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return dateFormat.format(calendar.getTime());
}
private JSONObject createSyncDossierBodyRequest(long groupId, Dossier dossier, JSONObject config,
String accessToken, HttpServletRequest request) {
JSONObject object = JSONFactoryUtil.createJSONObject();
String _oServiceCode = dossier.getServiceCode();
String _mServiceCode = StringPool.BLANK;
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchDVCQGServiceCode(groupId,
_oServiceCode);
if (serviceInfoMapping != null) {
_mServiceCode = serviceInfoMapping.getServiceCodeDVCQG();
}
_log.debug("
object.put("MaHoSo", dossier.getDossierNo());
object.put("MaTTHC", _mServiceCode);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "LayThuTuc");
body.put("maTTHC", _mServiceCode);
JSONObject serviceInfo = getSharingData(config, body, accessToken);
//get TenTTHC, MaLinhVuc, TenLinhVuc
String TenTTHC = StringPool.BLANK;
String MaLinhVuc = StringPool.BLANK;
String TenLinhVuc = StringPool.BLANK;
if (serviceInfo != null && serviceInfo.has("result")) {
JSONArray results = serviceInfo.getJSONArray("result");
if (results.length() > 0) {
JSONObject _tmp = results.getJSONObject(0);
TenTTHC = _tmp.getString("TENTTHC");
MaLinhVuc = _tmp.getJSONArray("LINHVUCTHUCHIEN").getJSONObject(0).getString("MALINHVUC");
TenLinhVuc = _tmp.getJSONArray("LINHVUCTHUCHIEN").getJSONObject(0).getString("TENLINHVUC");
}
}
object.put("TenTTHC", TenTTHC);
object.put("MaLinhVuc", MaLinhVuc);
object.put("TenLinhVuc", TenLinhVuc);
//object.put("SoBienNhan", ""); //ko bb
object.put("ChuHoSo", dossier.getContactName()); //ko bb
int LoaiDoiTuong = 1;
if (Validator.isNotNull(dossier.getApplicantIdType())) {
if ("business".equals(dossier.getApplicantIdType())) {
LoaiDoiTuong = 2;
}
}
Applicant applicant = ApplicantLocalServiceUtil.fetchByF_APLC_GID(groupId, dossier.getApplicantIdNo());
String madoituong = StringPool.BLANK;
if (applicant != null && "dvcqg".contentEquals(applicant.getMappingClassName())) {
madoituong = applicant.getMappingClassPK();
}
object.put("LoaiDoiTuong", String.valueOf(LoaiDoiTuong));
object.put("MaDoiTuong", madoituong); //ko bb
object.put("ThongTinKhac", ""); //ko bb
object.put("Email", dossier.getContactEmail());
object.put("Fax", dossier.getContactTelNo()); //ko bb
object.put("SoDienThoai", dossier.getContactTelNo());
object.put("TrichYeuHoSo", dossier.getDossierNote());
object.put("NgayTiepNhan", convertDate2String(dossier.getReceiveDate()));
object.put("NgayHenTra", convertDate2String(dossier.getDueDate()));
object.put("TrangThaiHoSo", getMappingStatus(groupId, dossier));
object.put("NgayTra", convertDate2String(dossier.getFinishDate()));//ko bb
object.put("ThongTinTra", "");//ko bb
int HinhThuc = 0;
if (dossier.getViaPostal() != 0 && dossier.getViaPostal() != 1) {
HinhThuc = 1;
}
object.put("HinhThuc", String.valueOf(HinhThuc));
object.put("NgayKetThucXuLy", convertDate2String(dossier.getReleaseDate()));//ko bb
object.put("DonViXuLy", dossier.getGovAgencyName());
object.put("GhiChu", dossier.getDossierNote());//ko bb
JSONArray DanhSachLePhi = JSONFactoryUtil.createJSONArray();
object.put("DanhSachLePhi", DanhSachLePhi);//ko bb
//object.put("TenPhiLePhi", "");
//object.put("MaPhiLePhi", "");
//object.put("HinhThucThu", "");
//object.put("Gia", "");
//object.put("LoaiPhiLePhi", "");
JSONArray DanhSachTepDinhKemKhac = JSONFactoryUtil.createJSONArray();
object.put("DanhSachTepDinhKemKhac", DanhSachTepDinhKemKhac);//ko bb
//object.put("TenGiayTo", "");
//object.put("SoLuong", "");
//object.put("LoaiGiayTo", "");
JSONArray DanhSachHoSoBoSung = JSONFactoryUtil.createJSONArray();
object.put("DanhSachHoSoBoSung", DanhSachHoSoBoSung);//ko bb
//object.put("HoSoBoSungId", "");
//object.put("NguoiYeuCauBoSung", "");
//object.put("NoiDungBoSung", "");
//object.put("NgayBoSung", "");
//object.put("NguoiTiepNhanBoSung", "");
//object.put("ThongTinTiepNhan", "");
//object.put("NgayTiepNhanBoSung", "");
//object.put("TrangThaiBoSung", "");
//object.put("DanhSachGiayToBoSung", "");
//object.put("DanhSachLePhiBoSung", "");
//object.put("NgayHenTraTruoc", "");
//object.put("NgayHenTraMoi", "");
List<DossierFile> dossierFiles = DossierFileLocalServiceUtil.getAllDossierFile(dossier.getDossierId());
if (dossierFiles != null) {
JSONArray DanhSachGiayToKetQua = JSONFactoryUtil.createJSONArray();
JSONObject data = null;
JSONArray TaiLieuNop = JSONFactoryUtil.createJSONArray();
for (DossierFile dossierFile : dossierFiles) {
if (!dossierFile.isRemoved() && dossierFile.getFileEntryId() > 0
&& dossierFile.getDossierPartType() > 0) {
try {
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierFile.getFileEntryId());
String url = StringPool.BLANK;
if (request != null) {
url = DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(),
(ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY), StringPool.BLANK);
} else {
StringBundler sb = new StringBundler(11);
sb.append(OpenCPSConfigUtil.getPortalDomain());
sb.append(PortalUtil.getPathContext());
sb.append("/documents/");
sb.append(fileEntry.getRepositoryId());
sb.append(StringPool.SLASH);
sb.append(fileEntry.getFolderId());
sb.append(StringPool.SLASH);
String fileName = fileEntry.getFileName();
sb.append(URLCodec.encodeURL(HtmlUtil.unescape(fileName)));
sb.append(StringPool.SLASH);
sb.append(URLCodec.encodeURL(fileEntry.getUuid()));
sb.append("?t=" + System.currentTimeMillis() + "&download=true");
url = sb.toString();
}
_log.debug("===> file URL " + url);
if (Validator.isNotNull(url)) {
data = JSONFactoryUtil.createJSONObject();
if (dossierFile.getDossierPartType() == 2) {
data.put("TenGiayTo", dossierFile.getDisplayName());
data.put("MaThanhPhanHoSo", dossierFile.getDossierPartNo());
data.put("GiayToId", String.valueOf(dossierFile.getDossierFileId()));
data.put("DuongDanTepTinKetQua", url);
DanhSachGiayToKetQua.put(data);
} else {
data.put("TenTepDinhKem", dossierFile.getDisplayName());
data.put("MaThanhPhanHoSo", dossierFile.getDossierPartNo());
data.put("TepDinhKemId", String.valueOf(dossierFile.getDossierFileId()));
data.put("DuongDanTaiTepTin", url);
data.put("IsDeleted", "False");
TaiLieuNop.put(data);
}
}
} catch (Exception e) {
_log.debug(e);
}
}
}
object.put("DanhSachGiayToKetQua", DanhSachGiayToKetQua);//ko bb
object.put("TaiLieuNop", TaiLieuNop);//ko bb
}
return object;
}
private JSONObject createSyncDossierBodyRequest(long groupId, Dossier dossier, ServerConfig serverConfig,
HttpServletRequest request) {
JSONObject object = JSONFactoryUtil.createJSONObject();
String _oServiceCode = dossier.getServiceCode();
String _mServiceCode = StringPool.BLANK;
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchDVCQGServiceCode(groupId,
_oServiceCode);
if (serviceInfoMapping != null) {
_mServiceCode = serviceInfoMapping.getServiceCodeDVCQG();
}
_log.debug("
object.put("MaHoSo", dossier.getDossierNo());
object.put("MaTTHC", _mServiceCode);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "LayThuTuc");
body.put("maTTHC", _mServiceCode);
JSONObject serviceInfo = getSharingData(serverConfig, body);
//get TenTTHC, MaLinhVuc, TenLinhVuc
String TenTTHC = StringPool.BLANK;
String MaLinhVuc = StringPool.BLANK;
String TenLinhVuc = StringPool.BLANK;
if (serviceInfo != null && serviceInfo.has("result")) {
JSONArray results = serviceInfo.getJSONArray("result");
if (results.length() > 0) {
JSONObject _tmp = results.getJSONObject(0);
TenTTHC = _tmp.getString("TENTTHC");
MaLinhVuc = _tmp.getJSONArray("LINHVUCTHUCHIEN").getJSONObject(0).getString("MALINHVUC");
TenLinhVuc = _tmp.getJSONArray("LINHVUCTHUCHIEN").getJSONObject(0).getString("TENLINHVUC");
}
}
object.put("TenTTHC", TenTTHC);
object.put("MaLinhVuc", MaLinhVuc);
object.put("TenLinhVuc", TenLinhVuc);
//object.put("SoBienNhan", ""); //ko bb
object.put("ChuHoSo", dossier.getContactName()); //ko bb
int LoaiDoiTuong = 1;
if (Validator.isNotNull(dossier.getApplicantIdType())) {
if ("business".equals(dossier.getApplicantIdType())) {
LoaiDoiTuong = 2;
}
}
object.put("LoaiDoiTuong", String.valueOf(LoaiDoiTuong));
Applicant applicant = ApplicantLocalServiceUtil.fetchByF_APLC_GID(groupId, dossier.getApplicantIdNo());
String madoituong = StringPool.BLANK;
if (applicant != null && "dvcqg".contentEquals(applicant.getMappingClassName())) {
madoituong = applicant.getMappingClassPK();
}
object.put("MaDoiTuong", madoituong); //ko bb
object.put("ThongTinKhac", ""); //ko bb
object.put("Email", dossier.getContactEmail());
object.put("Fax", dossier.getContactTelNo()); //ko bb
object.put("SoDienThoai", dossier.getContactTelNo());
object.put("TrichYeuHoSo", dossier.getDossierNote());
object.put("NgayTiepNhan", convertDate2String(dossier.getReceiveDate()));
object.put("NgayHenTra", convertDate2String(dossier.getDueDate()));
object.put("TrangThaiHoSo", getMappingStatus(groupId, dossier));
object.put("NgayTra", convertDate2String(dossier.getFinishDate()));//ko bb
object.put("ThongTinTra", "");//ko bb
int HinhThuc = 0;
if (dossier.getViaPostal() != 0 && dossier.getViaPostal() != 1) {
HinhThuc = 1;
}
object.put("HinhThuc", String.valueOf(HinhThuc));
object.put("NgayKetThucXuLy", convertDate2String(dossier.getReleaseDate()));//ko bb
object.put("DonViXuLy", dossier.getGovAgencyName());
object.put("GhiChu", dossier.getDossierNote());//ko bb
JSONArray DanhSachLePhi = JSONFactoryUtil.createJSONArray();
object.put("DanhSachLePhi", DanhSachLePhi);//ko bb
//object.put("TenPhiLePhi", "");
//object.put("MaPhiLePhi", "");
//object.put("HinhThucThu", "");
//object.put("Gia", "");
//object.put("LoaiPhiLePhi", "");
JSONArray DanhSachTepDinhKemKhac = JSONFactoryUtil.createJSONArray();
object.put("DanhSachTepDinhKemKhac", DanhSachTepDinhKemKhac);//ko bb
//object.put("TenGiayTo", "");
//object.put("SoLuong", "");
//object.put("LoaiGiayTo", "");
JSONArray DanhSachHoSoBoSung = JSONFactoryUtil.createJSONArray();
object.put("DanhSachHoSoBoSung", DanhSachHoSoBoSung);//ko bb
//object.put("HoSoBoSungId", "");
//object.put("NguoiYeuCauBoSung", "");
//object.put("NoiDungBoSung", "");
//object.put("NgayBoSung", "");
//object.put("NguoiTiepNhanBoSung", "");
//object.put("ThongTinTiepNhan", "");
//object.put("NgayTiepNhanBoSung", "");
//object.put("TrangThaiBoSung", "");
//object.put("DanhSachGiayToBoSung", "");
//object.put("DanhSachLePhiBoSung", "");
//object.put("NgayHenTraTruoc", "");
//object.put("NgayHenTraMoi", "");
List<DossierFile> dossierFiles = DossierFileLocalServiceUtil.getAllDossierFile(dossier.getDossierId());
if (dossierFiles != null) {
JSONArray DanhSachGiayToKetQua = JSONFactoryUtil.createJSONArray();
JSONObject data = null;
JSONArray TaiLieuNop = JSONFactoryUtil.createJSONArray();
for (DossierFile dossierFile : dossierFiles) {
if (!dossierFile.isRemoved() && dossierFile.getFileEntryId() > 0
&& dossierFile.getDossierPartType() > 0) {
try {
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(dossierFile.getFileEntryId());
String url = StringPool.BLANK;
if (request != null) {
url = DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(),
(ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY), StringPool.BLANK);
} else {
StringBundler sb = new StringBundler(11);
sb.append(OpenCPSConfigUtil.getPortalDomain());
sb.append(PortalUtil.getPathContext());
sb.append("/documents/");
sb.append(fileEntry.getRepositoryId());
sb.append(StringPool.SLASH);
sb.append(fileEntry.getFolderId());
sb.append(StringPool.SLASH);
String fileName = fileEntry.getFileName();
sb.append(URLCodec.encodeURL(HtmlUtil.unescape(fileName)));
sb.append(StringPool.SLASH);
sb.append(URLCodec.encodeURL(fileEntry.getUuid()));
sb.append("?t=" + System.currentTimeMillis() + "&download=true");
url = sb.toString();
}
_log.debug("===> file URL " + url);
if (Validator.isNotNull(url)) {
data = JSONFactoryUtil.createJSONObject();
if (dossierFile.getDossierPartType() == 2) {
data.put("TenGiayTo", dossierFile.getDisplayName());
data.put("MaThanhPhanHoSo", dossierFile.getDossierPartNo());
data.put("GiayToId", String.valueOf(dossierFile.getDossierFileId()));
data.put("DuongDanTepTinKetQua", url);
DanhSachGiayToKetQua.put(data);
} else {
data.put("TenTepDinhKem", dossierFile.getDisplayName());
data.put("MaThanhPhanHoSo", dossierFile.getDossierPartNo());
data.put("TepDinhKemId", String.valueOf(dossierFile.getDossierFileId()));
data.put("DuongDanTaiTepTin", url);
data.put("IsDeleted", "False");
TaiLieuNop.put(data);
}
}
} catch (Exception e) {
_log.debug(e);
}
}
}
object.put("DanhSachGiayToKetQua", DanhSachGiayToKetQua);//ko bb
object.put("TaiLieuNop", TaiLieuNop);//ko bb
}
return object;
}
private JSONObject createSyncDossierStatusBodyRequest(long groupId, Dossier dossier) {
JSONObject object = JSONFactoryUtil.createJSONObject();
object.put("MaHoSo", dossier.getDossierNo());
DossierAction dossierAction = DossierActionLocalServiceUtil.fetchDossierAction(dossier.getDossierActionId());
object.put("NguoiXuLy", dossierAction != null ? dossierAction.getActionUser() : StringPool.BLANK);
object.put("ChucDanh", "");//ko bb
object.put("ThoiDiemXuLy",
dossierAction != null ? convertDate2String(dossierAction.getCreateDate()) : StringPool.BLANK);
object.put("PhongBanXuLy", "");//ko bb
object.put("NoiDungXuLy", dossierAction != null ? dossierAction.getActionNote() : StringPool.BLANK);
object.put("TrangThai", getMappingStatus(groupId, dossier));
object.put("NgayBatDau", "");//ko bb
object.put("NgayKetThucTheoQuyDinh", "");//ko bb
return object;
}
@Override
public JSONObject doSyncGovernmentAgency(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject qajson = JSONFactoryUtil.createJSONObject();
JSONObject result = JSONFactoryUtil.createJSONObject();
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
if (!data.has("service")) {
data.put("service", "LayDanhMucCoQuan");
}
qajson = getSharingDictCollection(serverConfig, data);
if (qajson.has("error_code") && qajson.getInt("error_code") == 0 && qajson.has("result")
&& qajson.getJSONArray("result").length() > 0) {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
DictCollection collection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(
DataMGTConstants.GOVERNMENT_AGENCY, serviceContext.getScopeGroupId());
if (collection == null || config == null) {
return null;
}
JSONArray dmlst = qajson.getJSONArray("result");
JSONArray resultData = JSONFactoryUtil.createJSONArray();
JSONObject item = null;
for (int i = 0; i < dmlst.length(); i++) {
JSONObject dmobj = dmlst.getJSONObject(i);
String madonvi = dmobj.getString("MADONVI");
String tendonvi = dmobj.getString("TENDONVI");
String capdonvi = dmobj.getString("CAPDONVI");
DictItem dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(madonvi,
collection.getDictCollectionId(), serviceContext.getScopeGroupId());
if (dictItem != null) {
dictItem.setItemName(tendonvi);
dictItem.setModifiedDate(new Date());
dictItem.setUserId(user.getUserId());
dictItem.setUserName(user.getFullName());
dictItem = DictItemLocalServiceUtil.updateDictItem(dictItem);
} else {
dictItem = DictItemLocalServiceUtil.addDictItem(user.getUserId(),
serviceContext.getScopeGroupId(), collection.getDictCollectionId(), madonvi,
tendonvi, tendonvi, StringPool.BLANK, 0, String.valueOf(1),
GetterUtil.getInteger(capdonvi), StringPool.BLANK, serviceContext);
}
item = JSONFactoryUtil.createJSONObject();
item.put("dictItemId", dictItem.getDictItemId());
item.put("createDate",
Validator.isNotNull(dictItem.getCreateDate())
? APIDateTimeUtils.convertDateToString(dictItem.getCreateDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("modifiedDate",
Validator.isNotNull(dictItem.getModifiedDate())
? APIDateTimeUtils.convertDateToString(dictItem.getModifiedDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("itemCode", dictItem.getItemCode());
item.put("itemName", dictItem.getItemName());
item.put("itemNameEN", dictItem.getItemNameEN());
item.put("itemDescription", dictItem.getItemDescription());
item.put("level", dictItem.getLevel());
item.put("sibling", dictItem.getSibling());
item.put("treeIndex", dictItem.getTreeIndex());
item.put("parentItem", JSONFactoryUtil.createJSONObject());
item.put("groups", StringPool.BLANK);
resultData.put(item);
}
result.put("total", resultData.length());
result.put("data", resultData);
}
} catch (Exception e) {
_log.error(e);
}
}
return result;
}
@Override
public JSONObject doSyncServiceAdministration(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject qajson = JSONFactoryUtil.createJSONObject();
_log.info("-->>>>>>>> doSyncGovernmentAgency: " + serverConfigs + "|" + serverConfigs.size());
JSONObject result = JSONFactoryUtil.createJSONObject();
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
if (!data.has("service")) {
data.put("service", "LayDanhMucCoQuan");
}
qajson = getSharingDictCollection(serverConfig, data);
if (qajson.has("error_code") && qajson.getInt("error_code") == 0 && qajson.has("result")
&& qajson.getJSONArray("result").length() > 0) {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
DictCollection collection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(
DataMGTConstants.SERVICE_ADMINISTRATION, serviceContext.getScopeGroupId());
if (collection == null || config == null) {
return null;
}
JSONArray dmlst = qajson.getJSONArray("result");
JSONArray resultData = JSONFactoryUtil.createJSONArray();
JSONObject item = null;
for (int i = 0; i < dmlst.length(); i++) {
JSONObject dmobj = dmlst.getJSONObject(i);
String madonvi = dmobj.getString("MADONVI");
String tendonvi = dmobj.getString("TENDONVI");
String capdonvi = dmobj.getString("CAPDONVI");
DictItem dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(madonvi,
collection.getDictCollectionId(), serviceContext.getScopeGroupId());
if (dictItem != null) {
dictItem.setItemName(tendonvi);
dictItem.setModifiedDate(new Date());
dictItem.setUserId(user.getUserId());
dictItem.setUserName(user.getFullName());
dictItem = DictItemLocalServiceUtil.updateDictItem(dictItem);
} else {
dictItem = DictItemLocalServiceUtil.addDictItem(user.getUserId(),
serviceContext.getScopeGroupId(), collection.getDictCollectionId(), madonvi,
tendonvi, tendonvi, StringPool.BLANK, 0, String.valueOf(1),
GetterUtil.getInteger(capdonvi), StringPool.BLANK, serviceContext);
}
item = JSONFactoryUtil.createJSONObject();
item.put("dictItemId", dictItem.getDictItemId());
item.put("createDate",
Validator.isNotNull(dictItem.getCreateDate())
? APIDateTimeUtils.convertDateToString(dictItem.getCreateDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("modifiedDate",
Validator.isNotNull(dictItem.getModifiedDate())
? APIDateTimeUtils.convertDateToString(dictItem.getModifiedDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("itemCode", dictItem.getItemCode());
item.put("itemName", dictItem.getItemName());
item.put("itemNameEN", dictItem.getItemNameEN());
item.put("itemDescription", dictItem.getItemDescription());
item.put("level", dictItem.getLevel());
item.put("sibling", dictItem.getSibling());
item.put("treeIndex", dictItem.getTreeIndex());
item.put("parentItem", JSONFactoryUtil.createJSONObject());
item.put("groups", StringPool.BLANK);
resultData.put(item);
}
result.put("total", resultData.length());
result.put("data", resultData);
}
} catch (Exception e) {
_log.error(e);
}
}
return result;
}
@Override
public JSONObject doSyncServiceDomain(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject qajson = JSONFactoryUtil.createJSONObject();
_log.info("-->>>>>>>> doSyncServiceDomain: " + serverConfigs + "|" + serverConfigs.size());
JSONObject result = JSONFactoryUtil.createJSONObject();
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
if (!data.has("service")) {
data.put("service", "LayDanhMucLinhVuc");
}
qajson = getSharingDictCollection(serverConfig, data);
//_log.info("-->>>>>>>>>>>>>>>>>>>>> " + qajson);
if (qajson.has("error_code") && qajson.getInt("error_code") == 0 && qajson.has("result")
&& qajson.getJSONArray("result").length() > 0) {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
DictCollection collection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(
DataMGTConstants.SERVICE_DOMAIN, serviceContext.getScopeGroupId());
if (collection == null || config == null) {
return null;
}
JSONArray dmlst = qajson.getJSONArray("result");
String madonvi = config.getString("madonvi");
JSONArray resultData = JSONFactoryUtil.createJSONArray();
JSONObject item = null;
int count = 1;
for (int i = 0; i < dmlst.length(); i++) {
JSONObject dmobj = dmlst.getJSONObject(i);
String malinhvuc = dmobj.getString("MALINHVUC");
String tenlinhvuc = dmobj.getString("TENLINHVUC");
String manganh = dmobj.getString("MANGANH");
if (Validator.isNotNull(manganh) && manganh.equalsIgnoreCase(madonvi)) {
DictItem dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(malinhvuc,
collection.getDictCollectionId(), serviceContext.getScopeGroupId());
if (dictItem != null) {
dictItem.setItemName(tenlinhvuc);
dictItem.setModifiedDate(new Date());
dictItem.setUserId(user.getUserId());
dictItem.setUserName(user.getFullName());
dictItem = DictItemLocalServiceUtil.updateDictItem(dictItem);
} else {
dictItem = DictItemLocalServiceUtil.addDictItem(user.getUserId(),
serviceContext.getScopeGroupId(), collection.getDictCollectionId(), malinhvuc,
tenlinhvuc, tenlinhvuc, StringPool.BLANK, 0, String.valueOf(count), 0,
StringPool.BLANK, serviceContext);
}
item = JSONFactoryUtil.createJSONObject();
item.put("dictItemId", dictItem.getDictItemId());
item.put("createDate",
Validator.isNotNull(dictItem.getCreateDate())
? APIDateTimeUtils.convertDateToString(dictItem.getCreateDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("modifiedDate", Validator.isNotNull(dictItem.getModifiedDate())
? APIDateTimeUtils.convertDateToString(dictItem.getModifiedDate(),
APIDateTimeUtils._TIMESTAMP)
: StringPool.BLANK);
item.put("itemCode", dictItem.getItemCode());
item.put("itemName", dictItem.getItemName());
item.put("itemNameEN", dictItem.getItemNameEN());
item.put("itemDescription", dictItem.getItemDescription());
item.put("level", dictItem.getLevel());
item.put("sibling", dictItem.getSibling());
item.put("treeIndex", dictItem.getTreeIndex());
item.put("parentItem", JSONFactoryUtil.createJSONObject());
item.put("groups", StringPool.BLANK);
resultData.put(item);
count++;
}
}
result.put("total", resultData.length());
result.put("data", resultData);
}
} catch (Exception e) {
_log.error(e);
}
}
return result;
}
@Override
public JSONObject doSyncSharingQA(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONArray resultData = JSONFactoryUtil.createJSONArray();
_log.info("-->>>>>>>> doSyncSharingQA: " + serverConfigs + "|" + serverConfigs.size());
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
int syncType = -1;
if (data != null && data.length() > 0) {
if (data.has("service")) {
syncType = 1;
} else {
syncType = 2;
}
} else {
syncType = 0;
}
JSONObject qajson = JSONFactoryUtil.createJSONObject();
DictCollection domainCollection = DictCollectionLocalServiceUtil
.fetchByF_dictCollectionCode(DataMGTConstants.SERVICE_DOMAIN, serviceContext.getScopeGroupId());
DictCollection agencyCollection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(
DataMGTConstants.GOVERNMENT_AGENCY, serviceContext.getScopeGroupId());
if (syncType == 0) {
data.put("service", "LayDanhSachHoiDapGuiTuDVCQG");
qajson = getSharingData(serverConfig, data);
extractFAQResult(user, resultData, qajson, serviceContext, domainCollection.getDictCollectionId(),
agencyCollection.getDictCollectionId());
data.put("service", "LayDanhSachHoiDapBoCoQuan");
qajson = getSharingData(serverConfig, data);
extractFAQResult(user, resultData, qajson, serviceContext, domainCollection.getDictCollectionId(),
agencyCollection.getDictCollectionId());
} else if (syncType == 1) {
qajson = getSharingData(serverConfig, data);
extractFAQResult(user, resultData, qajson, serviceContext, domainCollection.getDictCollectionId(),
agencyCollection.getDictCollectionId());
} else if (syncType == 2) {
JSONArray result = JSONFactoryUtil.createJSONArray();
result.put(data);
qajson.put("result", result);
extractFAQResult(user, resultData, qajson, serviceContext, domainCollection.getDictCollectionId(),
agencyCollection.getDictCollectionId());
}
} catch (Exception e) {
_log.error(e);
}
}
JSONObject results = JSONFactoryUtil.createJSONObject();
results.put("total", resultData.length());
results.put("data", resultData);
return results;
}
private JSONArray extractFAQResult(User user, JSONArray resultData, JSONObject qajson,
ServiceContext serviceContext, long domainCollectionId, long agencyCollectionId) {
if (qajson.has("error_code") && qajson.getInt("error_code") == 0 && qajson.has("result")
&& qajson.getJSONArray("result").length() > 0) {
JSONArray qalst = qajson.getJSONArray("result");
JSONObject item = null;
for (int i = 0; i < qalst.length(); i++) {
item = JSONFactoryUtil.createJSONObject();
JSONObject qaobj = qalst.getJSONObject(i);
long hoidapid = qaobj.getLong("HOIDAPID");
if (hoidapid <= 0) {
continue;
}
String malinhvuc = StringPool.BLANK;
if (qaobj.has("MALINHVUC")) {
malinhvuc = qaobj.getString("MALINHVUC");
}
String tendonvi = StringPool.BLANK;
if (qaobj.has("TENDONVI")) {
tendonvi = qaobj.getString("TENDONVI");
}
String noidung = StringPool.BLANK;
if (qaobj.has("NOIDUNG")) {
noidung = qaobj.getString("NOIDUNG");
}
String madonvi = StringPool.BLANK;
if (qaobj.has("MADONVI")) {
madonvi = qaobj.getString("MADONVI");
}
String noidungtraloi = qaobj.getString("NOIDUNGTRALOI");
if (qaobj.has("NOIDUNGTRALOI")) {
noidungtraloi = qaobj.getString("NOIDUNGTRALOI");
}
long traloiid = 0;
if (qaobj.has("TRALOIID")) {
traloiid = qaobj.getLong("TRALOIID");
}
String hovaten = StringPool.BLANK;
if (qajson.has("HOVATEN")) {
hovaten = qaobj.getString("HOVATEN");
}
/*String diachi = StringPool.BLANK;
if (qajson.has("DIACHI")) {
diachi = qaobj.getString("DIACHI");
}*/
String thudientu = StringPool.BLANK;
if (qajson.has("THUDIENTU")) {
thudientu = qaobj.getString("THUDIENTU");
}
/*String sodienthoai = StringPool.BLANK;
if (qajson.has("SODIENTHOAI")) {
sodienthoai = qaobj.getString("SODIENTHOAI");
}*/
String matthcdp = StringPool.BLANK;
if (qajson.has("MATTHCDP")) {
matthcdp = qaobj.getString("MATTHCDP");
}
int trangthai = 1;
if (qajson.has("TRANGTHAI")) {
trangthai = qaobj.getInt("TRANGTHAI");
if (trangthai == 0) {
continue;
}
}
String domainName = StringPool.BLANK;
String domainCode = StringPool.BLANK;
String domainCodeTemp = StringPool.BLANK;
//Dung cho phuong an replace
if (Validator.isNotNull(malinhvuc)) {
//domainCode = malinhvuc;
domainCodeTemp = malinhvuc;
} else {
//domainCode = matthcdp;
domainCodeTemp = matthcdp;
}
DictItemMapping dictItemMapping1 = DictItemMappingLocalServiceUtil
.fetchByF_GID_ICDVCQG_CID(serviceContext.getScopeGroupId(), domainCodeTemp, domainCollectionId);
DictItemMapping dictItemMapping2 = DictItemMappingLocalServiceUtil
.fetchByF_GID_ICDVCQG_CID(serviceContext.getScopeGroupId(), madonvi, agencyCollectionId);
if (dictItemMapping1 == null || dictItemMapping2 == null) {
continue;
}
DictItem domainItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(dictItemMapping1.getItemCode(),
domainCollectionId, serviceContext.getScopeGroupId());
DictItem govAgencyItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(dictItemMapping2.getItemCode(),
agencyCollectionId, serviceContext.getScopeGroupId());
if (domainItem == null || govAgencyItem == null) {
continue;
}
domainCode = dictItemMapping1.getItemCode();
domainName = domainItem.getItemName();
Question question = QuestionLocalServiceUtil.fetchByG_CN_CPK(serviceContext.getScopeGroupId(),
"dvcqg_question", String.valueOf(hoidapid));
List<Long> traloiids = new ArrayList<Long>();
//chua dong bo
if (question == null) {
question = QuestionLocalServiceUtil.updateQuestion(serviceContext.getCompanyId(),
serviceContext.getScopeGroupId(), 0,
Validator.isNotNull(hovaten) ? hovaten : user.getFullName(), thudientu, noidung, trangthai,
domainCode, domainName, govAgencyItem.getItemCode(), govAgencyItem.getItemName(),
Validator.isNotNull(hovaten) ? "faq" : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
"dvcqg_question", String.valueOf(hoidapid), 1);
} else {
//da dong bo ->dong bo lai va lay d/s cau tra loi da dong bo
QuestionLocalServiceUtil.updateQuestion(serviceContext.getCompanyId(),
serviceContext.getScopeGroupId(), question.getQuestionId(),
Validator.isNotNull(hovaten) ? hovaten : user.getFullName(), thudientu, noidung, trangthai,
domainCode, domainName, govAgencyItem.getItemCode(), govAgencyItem.getItemName(),
Validator.isNotNull(hovaten) ? "faq" : StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
"dvcqg_question", String.valueOf(hoidapid), 1);
List<Answer> answers = AnswerLocalServiceUtil.findByG_Q(serviceContext.getScopeGroupId(),
question.getQuestionId());
if (answers != null) {
for (Answer answer : answers) {
if (Validator.isNotNull(answer.getClassName())
&& "dvcqg_answer".contentEquals(answer.getClassName())) {
traloiids.add(GetterUtil.getLong(answer.getClassPK()));
}
}
}
}
item.put("questionId", question.getQuestionId());
item.put("createDate", APIDateTimeUtils.convertDateToString(question.getCreateDate()));
item.put("fullname", question.getFullname());
item.put("email", question.getEmail());
item.put("content", question.getContent());
item.put("publish", question.getPublish());
item.put("questionType", question.getQuestionType());
item.put("domainCode", question.getDomainCode());
item.put("domainName", question.getDomainName());
item.put("govAgencyCode", question.getGovAgencyCode());
item.put("govAgencyName", question.getGovAgencyName());
item.put("answered", traloiid > 0 ? true : false);
item.put("subDomainCode", question.getSubDomainCode());
item.put("subDomainName", question.getSubDomainName());
resultData.put(item);
//dong bo cau tra loi
if (traloiid > 0 && Validator.isNotNull(noidungtraloi) && !traloiids.contains(traloiid)) {
AnswerLocalServiceUtil.updateAnswer(user.getUserId(), serviceContext.getScopeGroupId(), 0,
question.getQuestionId(), noidungtraloi, 1, "dvcqg_answer", String.valueOf(traloiid), 1);
} else if (traloiid <= 0) {
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "LayNoiDungTraLoiTheoCauHoi");
body.put("cauhoiid", hoidapid);
JSONArray answerArr = getAnswer(user, serviceContext, body);
if (answerArr != null) {
for (int j = 0; j < answerArr.length(); j++) {
JSONObject asobj = answerArr.getJSONObject(i);
traloiid = asobj.getLong("TRALOIID");
noidungtraloi = asobj.getString("NOIDUNGTRALOI");
if (traloiid > 0 && Validator.isNotNull(noidungtraloi) && !traloiids.contains(traloiid)) {
AnswerLocalServiceUtil.updateAnswer(user.getUserId(), serviceContext.getScopeGroupId(),
0, question.getQuestionId(), noidungtraloi, 1, "dvcqg_answer",
String.valueOf(traloiid), 1);
}
}
}
}
}
}
return resultData;
}
private String getAccessToken(long companyId, long groupId, String className, JSONObject config) {
AccessToken accessToken = AccessTokenLocalServiceUtil.getAccessToken(groupId, className);
if (accessToken != null) {
_log.info("getAccesToken form DB " + accessToken.getToken());
return accessToken.getToken();
}
HttpURLConnection conn = null;
try {
_log.debug("config: " + config.toJSONString());
String adapter_url = config.getString("adapter_url");
String auth_endpoint = config.getString("auth_endpoint");
String username = config.getString("username");
String password = config.getString("password");
String dstcode = config.getString("dstcode");
_log.debug("dstcode: " + dstcode);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("username", username);
body.put("password", password);
String endpoint = adapter_url + auth_endpoint;
URL url = new URL(endpoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("dstcode", dstcode);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(60 * 1000);
byte[] postData = body.toJSONString().getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
String output = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
sb.append(output);
}
System.out.println("response: " + sb.toString());
JSONObject result = JSONFactoryUtil.createJSONObject(sb.toString());
if (result.has("session") && result.has("error_code") && result.getInt("error_code") == 0) {
String session = result.getString("session");
AccessTokenLocalServiceUtil.addAccessToken(companyId, groupId, session, className);
return session;
}
return StringPool.BLANK;
}
} catch (Exception e) {
_log.error(e);
return StringPool.BLANK;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private String getAccessToken(ServerConfig serverConfig) {
//HttpURLConnection conn = null;
try {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
return getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg", config);
} catch (Exception e) {
_log.error(e);
return StringPool.BLANK;
}
// finally {
// if (conn != null) {
// conn.disconnect();
}
@Override
public String getAccessToken(User user, HttpServletRequest request, HttpServletResponse response,
ServiceContext serviceContext) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
String accessToken = getAccessToken(serverConfig);
/*HttpSession session = request.getSession();
String accessToken = (String)session.getAttribute("ACCESS_TOKEN");
if(Validator.isNull(accessToken)) {
accessToken = getAccessToken(serverConfig);
session.setAttribute("ACCESS_TOKEN", accessToken);
}*/
return accessToken;
}
return StringPool.BLANK;
}
private JSONArray getAnswer(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject qajson = JSONFactoryUtil.createJSONObject();
_log.info("-->>>>>>>> syncAnswer: " + serverConfigs + "|" + serverConfigs.size());
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
qajson = getSharingData(serverConfig, data);
if (qajson.has("error_code") && qajson.getInt("error_code") == 0 && qajson.has("result")
&& qajson.getJSONArray("result").length() > 0) {
JSONArray qalst = qajson.getJSONArray("result");
return qalst;
}
} catch (Exception e) {
_log.error(e);
}
}
return null;
}
public String getMappingStatus(long groupId, Dossier dossier) {
if (Validator.isNotNull(dossier.getDossierSubStatus())) {
DossierStatusMapping statusMapping = DossierStatusMappingLocalServiceUtil.fetchByF_GID_SUBSC(groupId,
dossier.getDossierSubStatus());
if (statusMapping != null) {
return statusMapping.getStatusCodeDVCQG();
}
}
List<DossierStatusMapping> statusMappings = DossierStatusMappingLocalServiceUtil.findByF_GID_SC(groupId,
dossier.getDossierStatus());
if (statusMappings != null && !statusMappings.isEmpty()) {
return statusMappings.get(0).getStatusCodeDVCQG();
}
return StringPool.BLANK;
}
@Deprecated
public HashMap<String, String> getServiceInfoDVCQGMap(User user, ServiceContext serviceContext) {
HashMap<String, String> serviceInfoDVCQGMap = new HashMap<String, String>();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put("service", "LayDanhSachTTHC");
JSONObject responseData = getSharingDictCollection(serverConfig, data);
if (responseData != null && responseData.has("result")) {
JSONArray result = responseData.getJSONArray("result");
JSONObject item;
for (int i = 0; i < result.length(); i++) {
item = result.getJSONObject(i);
serviceInfoDVCQGMap.put(item.getString("MATTHC"), item.getString("TENTTHC"));
}
}
}
return serviceInfoDVCQGMap;
}
public JSONObject getServiceInfoDVCQGDetail(User user, long groupId, ServiceContext serviceContext, String code) {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put("service", "LayThuTuc");
data.put("maTTHC", code);
result = getSharingData(serverConfig, data);
}
return result;
}
public JSONArray getServiceInfoDVCQG(User user, long groupId, ServiceContext serviceContext, String serviceCode,
String serviceName) {
JSONArray result = JSONFactoryUtil.createJSONArray();
if (_serviceInfoDVCQG.length() == 0) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put("service", "LayDanhSachTTHC");
JSONObject responseData = getSharingDictCollection(serverConfig, data);
if (responseData != null && responseData.has("result")) {
_serviceInfoDVCQG = responseData.getJSONArray("result");
}
}
}
JSONObject item;
JSONObject dataRow = null;
for (int i = 0; i < _serviceInfoDVCQG.length(); i++) {
item = _serviceInfoDVCQG.getJSONObject(i);
dataRow = JSONFactoryUtil.createJSONObject();
String serviceCodeDVCQG = item.getString("MATTHC");
dataRow.put("serviceCodeDVCQG", serviceCodeDVCQG);
dataRow.put("serviceNameDVCQG", item.getString("TENTTHC"));
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchByGID_SCDVCQG(groupId,
serviceCodeDVCQG);
if (serviceInfoMapping == null) {
dataRow.put("serviceCode", StringPool.BLANK);
dataRow.put("serviceName", StringPool.BLANK);
dataRow.put("mapping", String.valueOf(false));
dataRow.put("synced", 0);
dataRow.put("mappingClassPK", 0);
dataRow.put("mappingClassPK", 0);
dataRow.put("serviceInfoId", 0);
} else {
String tmpServiceCode = serviceInfoMapping.getServiceCode();
ServiceInfo serviceInfo = null;
try {
serviceInfo = ServiceInfoLocalServiceUtil.getByCode(groupId, tmpServiceCode);
} catch (Exception e) {
_log.warn(e);
}
String tmpServiceName = serviceInfo != null ? serviceInfo.getServiceName() : StringPool.BLANK;
dataRow.put("serviceCode", tmpServiceCode);
dataRow.put("serviceName", tmpServiceName);
dataRow.put("mapping", String.valueOf(true));
dataRow.put("synced", serviceInfoMapping.getSynced());
dataRow.put("mappingClassPK", serviceInfoMapping.getServiceInfoMappingId());
dataRow.put("serviceInfoId", serviceInfo != null ? serviceInfo.getServiceInfoId() : 0);
}
result.put(dataRow);
}
return result;
}
public HashMap<String, String> getDictItemDVCQGMap(User user, ServiceContext serviceContext, String service) {
HashMap<String, String> dictItemDVCQGMap = new HashMap<String, String>();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject data = JSONFactoryUtil.createJSONObject();
data.put("service", service);
JSONObject responseData = getSharingDictCollection(serverConfig, data);
if (responseData != null && responseData.has("result")) {
JSONArray result = responseData.getJSONArray("result");
JSONObject item;
for (int i = 0; i < result.length(); i++) {
item = result.getJSONObject(i);
if ("LayDanhMucLinhVuc".equals(service)) {
dictItemDVCQGMap.put(item.getString("MALINHVUC"), item.getString("TENLINHVUC"));
} else if ("LayDanhMucCoQuan".equals(service)) {
dictItemDVCQGMap.put(item.getString("MADONVI"), item.getString("TENDONVI"));
}
}
}
}
return dictItemDVCQGMap;
}
public JSONObject getDictItemDVCQG(User user, ServiceContext serviceContext, String service) {
JSONArray data = JSONFactoryUtil.createJSONArray();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", service);
JSONObject responseData = getSharingDictCollection(serverConfig, body);
if (responseData != null && responseData.has("result")) {
JSONArray result = responseData.getJSONArray("result");
JSONObject item;
for (int i = 0; i < result.length(); i++) {
JSONObject dataRow = JSONFactoryUtil.createJSONObject();
item = result.getJSONObject(i);
if ("LayDanhMucLinhVuc".equals(service)) {
dataRow.put("itemCodeDVCQG", item.getString("MALINHVUC"));
dataRow.put("itemNameDVCQG", item.getString("TENLINHVUC"));
data.put(dataRow);
} else if ("LayDanhMucCoQuan".equals(service)) {
dataRow.put("itemCodeDVCQG", item.getString("MADONVI"));
dataRow.put("itemNameDVCQG", item.getString("TENDONVI"));
data.put(dataRow);
}
}
}
}
JSONObject result = JSONFactoryUtil.createJSONObject();
result.put("total", data.length());
result.put("data", data);
return result;
}
@Deprecated
public JSONArray getServiceInfoSimilarity(long groupId, String serviceCode, String serviceName,
HashMap<String, String> map) {
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchDVCQGServiceCode(groupId,
serviceCode);
String _tmpServiceName = serviceName.replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
JSONArray result = JSONFactoryUtil.createJSONArray();
if (serviceInfoMapping != null) {
JSONObject item = JSONFactoryUtil.createJSONObject();
String serviceNameDVCQG = map.get(serviceInfoMapping.getServiceCodeDVCQG());
item.put("serviceCodeDVCQG", serviceInfoMapping.getServiceCodeDVCQG());
item.put("serviceInfoMappingId", serviceInfoMapping.getServiceInfoMappingId());
item.put("serviceNameDVCQG", serviceNameDVCQG);
item.put("similarityPercent", 100);
item.put("mapped", true);
result.put(item);
return result;
}
Map<CharSequence, Integer> vectorA = Arrays.stream(_tmpServiceName.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
SortedMap<Double, JSONObject> sortedMap = new TreeMap<Double, JSONObject>(Collections.reverseOrder());
CosineSimilarity documentsSimilarity = new CosineSimilarity();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
if (_serviceInfoMapChars != null && !_serviceInfoMapChars.isEmpty()) {
_log.info("
+ _serviceInfoMapChars.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String name = entry.getValue().replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
//_log.info(key + "|" + name);
Map<CharSequence, Integer> vectorB = null;
if (_serviceInfoMapChars.containsKey(key)) {
vectorB = _serviceInfoMapChars.get(key);
} else {
vectorB = Arrays.stream(name.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
_serviceInfoMapChars.put(key, vectorB);
}
Double weightIndex = documentsSimilarity.cosineSimilarity(vectorA, vectorB);
//_log.info(weightIndex);
JSONObject item = null;
if (_serviceInfoMapItems != null && _serviceInfoMapItems.containsKey(key)) {
item = _serviceInfoMapItems.get(key);
item.put("similarityPercent", df.format(weightIndex * 100));
} else {
item = JSONFactoryUtil.createJSONObject();
item.put("serviceCodeDVCQG", key);
item.put("serviceNameDVCQG", entry.getValue());
item.put("mapped", false);
item.put("serviceInfoMappingId", 0);
_serviceInfoMapItems.put(key, item);
}
if (weightIndex >= 0.4) {
item.put("similarityPercent", df.format(weightIndex * 100));
if (weightIndex >= 1) {
result.put(item);
return result;
}
sortedMap.put(weightIndex, item);
}
}
} else {
_log.info("
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String name = entry.getValue().replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
Map<CharSequence, Integer> vectorB = Arrays.stream(name.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
_serviceInfoMapChars.put(key, vectorB);
Double weightIndex = documentsSimilarity.cosineSimilarity(vectorA, vectorB);
JSONObject item = JSONFactoryUtil.createJSONObject();
item.put("serviceCodeDVCQG", key);
item.put("serviceNameDVCQG", entry.getValue());
item.put("serviceInfoMappingId", 0);
item.put("mapped", false);
_serviceInfoMapItems.put(key, item);
if (weightIndex >= 0.4) {
item.put("similarityPercent", df.format(weightIndex * 100));
if (weightIndex >= 1) {
result.put(item);
return result;
}
sortedMap.put(weightIndex, item);
}
}
}
if (!sortedMap.isEmpty()) {
for (Map.Entry<Double, JSONObject> entry : sortedMap.entrySet()) {
result.put(entry.getValue());
}
}
return result;
}
public JSONArray getDictItemSimilarity(long groupId, String collectionCode, String dictItemCode,
String dictItemName, HashMap<String, String> map, List<String> mappedCode) {
JSONArray result = JSONFactoryUtil.createJSONArray();
DictCollection dictCollection = DictCollectionLocalServiceUtil.fetchByF_dictCollectionCode(collectionCode,
groupId);
if (dictCollection == null) {
return result;
}
DictItemMapping dicItemMapping = DictItemMappingLocalServiceUtil.fetchByF_GID_IC_CID(groupId, dictItemCode,
dictCollection.getDictCollectionId());
String _tmpDictItemName = dictItemName.replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
if (dicItemMapping != null) {
JSONObject item = JSONFactoryUtil.createJSONObject();
String itemNameDVCQG = map.get(dicItemMapping.getItemCodeDVCQG());
item.put("itemCodeDVCQG", dicItemMapping.getItemCodeDVCQG());
item.put("dictItemMappingId", dicItemMapping.getMappingId());
item.put("itemNameDVCQG", itemNameDVCQG);
item.put("similarityPercent", 100);
item.put("mapped", true);
result.put(item);
return result;
}
Map<CharSequence, Integer> vectorA = Arrays.stream(_tmpDictItemName.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
SortedMap<Double, JSONObject> sortedMap = new TreeMap<Double, JSONObject>(Collections.reverseOrder());
CosineSimilarity documentsSimilarity = new CosineSimilarity();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
if (_dictItemMapChars != null && !_dictItemMapChars.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (mappedCode.contains(key)) {
continue;
}
String name = entry.getValue().replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
Map<CharSequence, Integer> vectorB = null;
if (_dictItemMapChars.containsKey(key)) {
vectorB = _dictItemMapChars.get(key);
} else {
vectorB = Arrays.stream(name.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
_dictItemMapChars.put(key, vectorB);
}
Double weightIndex = documentsSimilarity.cosineSimilarity(vectorA, vectorB);
JSONObject item = null;
if (_dictItemMapItems != null && _dictItemMapItems.containsKey(key)) {
item = _dictItemMapItems.get(key);
item.put("similarityPercent", df.format(weightIndex * 100));
} else {
item = JSONFactoryUtil.createJSONObject();
item.put("itemCodeDVCQG", key);
item.put("itemNameDVCQG", entry.getValue());
item.put("mapped", false);
item.put("dictItemMappingId", 0);
_dictItemMapItems.put(key, item);
}
if (weightIndex >= 0.4) {
item.put("similarityPercent", df.format(weightIndex * 100));
if (weightIndex >= 1) {
result.put(item);
return result;
}
sortedMap.put(weightIndex, item);
}
}
} else {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (mappedCode.contains(key)) {
continue;
}
String name = entry.getValue().replaceAll("[.,\\-_:;\\\"\\']", "").toLowerCase();
Map<CharSequence, Integer> vectorB = Arrays.stream(name.split(" "))
.collect(Collectors.toMap(character -> character, character -> 1, Integer::sum));
_dictItemMapChars.put(key, vectorB);
Double weightIndex = documentsSimilarity.cosineSimilarity(vectorA, vectorB);
JSONObject item = JSONFactoryUtil.createJSONObject();
item.put("itemCodeDVCQG", key);
item.put("itemNameDVCQG", entry.getValue());
item.put("dictItemMappingId", 0);
item.put("mapped", false);
_dictItemMapItems.put(key, item);
if (weightIndex >= 0.4) {
item.put("similarityPercent", df.format(weightIndex * 100));
if (weightIndex >= 1) {
result.put(item);
return result;
}
sortedMap.put(weightIndex, item);
}
}
}
if (!sortedMap.isEmpty()) {
for (Map.Entry<Double, JSONObject> entry : sortedMap.entrySet()) {
result.put(entry.getValue());
}
}
return result;
}
private JSONObject getSharingData(JSONObject config, JSONObject data, String accessToken) {
HttpURLConnection conn = null;
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
String adapter_url = config.getString("adapter_url");
String integration_endpoint = config.getString("integration_endpoint");
String madonvi = config.getString("madonvi");
String dstcode = config.getString("dstcode");
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("session", accessToken);
body.put("madonvi", madonvi);
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
body.put(key, data.get(key));
}
String endpoint = adapter_url + integration_endpoint;
URL url = new URL(endpoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("dstcode", dstcode);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(60 * 1000);
byte[] postData = body.toJSONString().getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
String output = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
sb.append(output);
}
//System.out.println("response: " + sb.toString());
result = JSONFactoryUtil.createJSONObject(sb.toString());
return result;
}
} catch (Exception e) {
_log.error(e);
return result;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private JSONObject getSharingData(ServerConfig serverConfig, JSONObject data) {
HttpURLConnection conn = null;
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
String adapter_url = config.getString("adapter_url");
String integration_endpoint = config.getString("integration_endpoint");
String madonvi = config.getString("madonvi");
String accessToken = getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg",
config);
String dstcode = config.getString("dstcode");
if (Validator.isNull(accessToken) || Validator.isNull(data)) {
return result;
}
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("session", accessToken);
body.put("madonvi", madonvi);
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
body.put(key, data.get(key));
}
String endpoint = adapter_url + integration_endpoint;
URL url = new URL(endpoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("dstcode", dstcode);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(60 * 1000);
byte[] postData = body.toJSONString().getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
String output = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
sb.append(output);
}
result = JSONFactoryUtil.createJSONObject(sb.toString());
return result;
}
} catch (Exception e) {
_log.error(e);
return result;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
@Override
public JSONObject getSharingData(User user, ServiceContext serviceContext, JSONObject data) {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
return getSharingData(serverConfig, data);
}
return result;
}
private JSONObject getSharingDictCollection(ServerConfig serverConfig, JSONObject data) {
HttpURLConnection conn = null;
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
String adapter_url = config.getString("adapter_url");
String share_endpoint = config.getString("share_endpoint");
String madonvi = config.getString("madonvi");
String dstcode = config.getString("dstcode");
String accessToken = getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg",
config);
if (Validator.isNull(accessToken) || Validator.isNull(data)) {
return result;
}
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("session", accessToken);
body.put("madonvi", madonvi);
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
body.put(key, data.get(key));
}
String endpoint = adapter_url + share_endpoint;
URL url = new URL(endpoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("dstcode", dstcode);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(60 * 1000);
byte[] postData = body.toJSONString().getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
String output = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
sb.append(output);
}
//System.out.println("response: " + sb.toString());
result = JSONFactoryUtil.createJSONObject(sb.toString());
return result;
}
} catch (Exception e) {
_log.error(e);
return result;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
@Override
public JSONObject getSharingDictCollection(User user, ServiceContext serviceContext, JSONObject data) {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
return getSharingDictCollection(serverConfig, data);
}
return result;
}
@Override
public JSONObject getSharingQA(User user, ServiceContext serviceContext, JSONObject data) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject result = JSONFactoryUtil.createJSONObject();
_log.info("-->>>>>>>> getSharingQA: " + serverConfigs + "|" + serverConfigs.size());
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
result = getSharingData(serverConfig, data);
} catch (Exception e) {
_log.error(e);
}
}
return result;
}
private boolean hasSyncDossier(String dossierNo, JSONObject config, String accessToken) {
JSONObject searchData = searchDossier(dossierNo, config, accessToken);
if (searchData != null && searchData.has("result")) {
JSONArray result = searchData.getJSONArray("result");
if (result != null && result.length() > 0) {
return true;
}
}
return false;
}
@Override
public JSONObject mappingServiceInfo(User user, long groupId, ServiceContext serviceContext, String serviceCode,
String serviceCodeDVCQG, String serviceNameDVCQG) {
JSONObject result = JSONFactoryUtil.createJSONObject();
if (Validator.isNotNull(serviceCode) && Validator.isNotNull(serviceCodeDVCQG)) {
try {
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchByGID_SCDVCQG(groupId,
serviceCodeDVCQG);
if (serviceInfoMapping != null) {
ServiceInfoMappingLocalServiceUtil
.removeServiceInfoMapping(serviceInfoMapping.getServiceInfoMappingId());
}
serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.fetchDVCQGServiceCode(groupId, serviceCode);
if (serviceInfoMapping != null) {
ServiceInfoMappingLocalServiceUtil
.removeServiceInfoMapping(serviceInfoMapping.getServiceInfoMappingId());
}
serviceInfoMapping = ServiceInfoMappingLocalServiceUtil.addServiceInfoMapping(groupId,
serviceContext.getCompanyId(), user.getUserId(), serviceCode, serviceCodeDVCQG,
serviceNameDVCQG, 0);
result.put("id", serviceInfoMapping.getServiceInfoMappingId());
result.put("serviceCode", serviceCode);
result.put("serviceCodeDVCQG", serviceCodeDVCQG);
result.put("serviceInfoMappingId", serviceInfoMapping.getServiceInfoMappingId());
result.put("groupId", serviceInfoMapping.getGroupId());
result.put("userId", serviceInfoMapping.getUserId());
} catch (Exception e) {
_log.error(e);
}
}
return result;
}
@Override
public boolean removeMappingServiceInfo(User user, long groupId, ServiceContext serviceContext, long id) {
return ServiceInfoMappingLocalServiceUtil.removeServiceInfoMapping(id);
}
private JSONObject searchDossier(String dossierNo, JSONObject config, String accessToken) {
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "TraCuuHoSo");
body.put("mahoso", dossierNo);
return getSharingData(config, body, accessToken);
}
private JSONObject syncData(ServerConfig serverConfig, JSONObject data) {
HttpURLConnection conn = null;
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
_log.debug("config->>> " + config.toJSONString());
String adapter_url = config.getString("adapter_url");
String integration_endpoint = config.getString("integration_endpoint");
String madonvi = config.getString("madonvi");
String accessToken = getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg",
config);
String dstcode = config.getString("dstcode");
if (Validator.isNull(accessToken) || Validator.isNull(data)) {
return result;
}
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("session", accessToken);
body.put("madonvi", madonvi);
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
body.put(key, data.get(key));
}
String endpoint = adapter_url + integration_endpoint;
URL url = new URL(endpoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("dstcode", dstcode);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(60 * 1000);
byte[] postData = body.toJSONString().getBytes("UTF-8");
int postDataLength = postData.length;
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
String output = StringPool.BLANK;
StringBuilder sb = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
sb.append(output);
}
_log.debug("response: " + sb.toString());
result = JSONFactoryUtil.createJSONObject(sb.toString());
return result;
}
} catch (Exception e) {
_log.error(e);
return result;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
@Override
public JSONObject syncDossier(User user, long groupId, ServiceContext serviceContext, String strDossierId,
String isUpdating, HttpServletRequest request) {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty() && Validator.isNotNull(strDossierId)) {
ServerConfig serverConfig = serverConfigs.get(0);
long[] dossierIds = StringUtil.split(strDossierId, 0L);
JSONArray synsObjects = JSONFactoryUtil.createJSONArray();
for (long dossierId : dossierIds) {
if (dossierId > 0) {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
if (dossier == null) {
continue;
}
JSONObject synsObject = createSyncDossierBodyRequest(groupId, dossier, serverConfig, request);
_log.debug(synsObject.toJSONString());
synsObjects.put(synsObject);
}
}
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("isUpdating", isUpdating);
body.put("service", "DongBoHoSoMC");
body.put("data", synsObjects);
return syncData(serverConfig, body);
}
return result;
}
public JSONObject syncDossierAndDossierStatus(long groupId, Dossier dossier, HttpServletRequest request)
throws JSONException {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
String accessToken = getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg",
config);
JSONArray synsObjects = JSONFactoryUtil.createJSONArray();
if (Validator.isNotNull(accessToken)) {
boolean hasSync = hasSyncDossier(dossier.getDossierNo(), config, accessToken);
JSONObject synsObject = createSyncDossierBodyRequest(groupId, dossier, config, accessToken, request);
synsObjects.put(synsObject);
_log.debug("syncDossierAndDossierStatus synsObjects " + synsObjects.toJSONString());
JSONObject body = JSONFactoryUtil.createJSONObject();
if (hasSync) {
body.put("isUpdating", "True");
} else {
body.put("isUpdating", "False");
}
body.put("data", synsObjects);
body.put("service", "DongBoHoSoMC");
result = syncData(serverConfig, body);
_log.debug("syncDossierAndDossierStatus " + result.toJSONString());
if (result.has("error_code") && GetterUtil.getInteger(result.getString("error_code")) == 0) {
body = JSONFactoryUtil.createJSONObject();
synsObjects = JSONFactoryUtil.createJSONArray();
JSONObject _tmp = createSyncDossierStatusBodyRequest(groupId, dossier);
synsObjects.put(_tmp);
_log.debug("syncDossierAndDossierStatus synsObjects " + synsObjects.toJSONString());
body.put("service", "CapNhatTienDoHoSoMC");
body.put("data", synsObjects);
result = syncData(serverConfig, body);
}
}
}
return result;
}
@Override
public JSONObject syncDossierStatus(User user, long groupId, ServiceContext serviceContext, String strDossierId,
HttpServletRequest request) {
JSONObject result = JSONFactoryUtil.createJSONObject();
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty() && Validator.isNotNull(strDossierId)) {
ServerConfig serverConfig = serverConfigs.get(0);
long[] dossierIds = StringUtil.split(strDossierId, 0L);
JSONArray synsObjects = JSONFactoryUtil.createJSONArray();
for (long dossierId : dossierIds) {
if (dossierId > 0) {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
if (dossier == null) {
continue;
}
JSONObject synsObject = createSyncDossierStatusBodyRequest(groupId, dossier);
synsObjects.put(synsObject);
}
}
_log.debug("syncDossierStatus " + synsObjects);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "CapNhatTienDoHoSoMC");
body.put("data", synsObjects);
return syncData(serverConfig, body);
}
return result;
}
@Override
public JSONObject syncServiceInfo(User user, long groupId, ServiceContext serviceContext, String serviceCodes,
String type) {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
JSONObject result = JSONFactoryUtil.createJSONObject();
JSONArray responseData = JSONFactoryUtil.createJSONArray();
//_log.info("-->>>>>>>> syncServiceInfo: " + serverConfigs + "|" + serverConfigs.size());
if (serverConfigs != null && !serverConfigs.isEmpty()) {
try {
ServerConfig serverConfig = serverConfigs.get(0);
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
String accessToken = getAccessToken(serverConfig.getCompanyId(), serverConfig.getGroupId(), "dvcqg",
config);
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "LayThuTuc");
DictCollection collection1 = DictCollectionLocalServiceUtil
.fetchByF_dictCollectionCode(DataMGTConstants.SERVICE_DOMAIN, groupId);
DictCollection collection2 = DictCollectionLocalServiceUtil
.fetchByF_dictCollectionCode(DataMGTConstants.GOVERNMENT_AGENCY, groupId);
if (Validator.isNotNull(serviceCodes)) {
String[] arrayServiceCode = StringUtil.split(serviceCodes);
for (String serviceCode : arrayServiceCode) {
ServiceInfo serviceInfo = ServiceInfoLocalServiceUtil.getByCode(groupId, serviceCode);
if (serviceInfo != null && type.equalsIgnoreCase("sync")) {
String serviceCodeDVCQG = StringPool.BLANK;
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil
.fetchDVCQGServiceCode(groupId, serviceCode);
if (serviceInfoMapping == null) {
continue;
}
serviceCodeDVCQG = serviceInfoMapping.getServiceCodeDVCQG();
JSONObject response = syncServiceInfo(user, groupId, config, serviceCodeDVCQG, serviceInfo,
collection1.getDictCollectionId(), collection2.getDictCollectionId(), body,
accessToken, serviceContext, type);
responseData.put(response);
}
if ("create".equals(type)) {
serviceInfo = new ServiceInfoImpl();
JSONObject response = syncServiceInfo(user, groupId, config, serviceCode, serviceInfo,
collection1.getDictCollectionId(), collection2.getDictCollectionId(), body,
accessToken, serviceContext, type);
responseData.put(response);
}
}
} else {
if ("sync".equals(type)) {
List<ServiceInfo> serviceInfos = ServiceInfoLocalServiceUtil.getServiceInfosByGroupId(groupId);
if (serviceInfos != null) {
for (ServiceInfo serviceInfo : serviceInfos) {
ServiceInfoMapping serviceInfoMapping = ServiceInfoMappingLocalServiceUtil
.fetchDVCQGServiceCode(groupId, serviceInfo.getServiceCode());
if (serviceInfoMapping == null || serviceInfoMapping.getSynced() == 1) {
continue;
}
JSONObject response = syncServiceInfo(user, groupId, config,
serviceInfoMapping.getServiceCodeDVCQG(), serviceInfo,
collection1.getDictCollectionId(), collection2.getDictCollectionId(), body,
accessToken, serviceContext, type);
responseData.put(response);
}
}
}
}
} catch (Exception e) {
_log.error(e);
}
}
result.put("total", responseData.length());
result.put("data", responseData);
return result;
}
//TODO
private JSONObject syncServiceInfo(User user, long groupId, JSONObject config, String serviceCodeDVCQG,
ServiceInfo serviceInfo, long domainCollectionId, long govAgencyCollectionId, JSONObject body,
String accessToken, ServiceContext serviceContext, String type) {
JSONObject result = JSONFactoryUtil.createJSONObject();
body.put("maTTHC", serviceCodeDVCQG);
JSONObject serviceInfoDVCQG = getSharingData(config, body, accessToken);
//String _oldServiceCode = serviceInfo.getServiceCode();
if (serviceInfoDVCQG != null && serviceInfoDVCQG.has("result")) {
JSONArray results = serviceInfoDVCQG.getJSONArray("result");
if (results.length() > 0) {
JSONObject _tmp = results.getJSONObject(0);
StringBuffer sb = null;
_log.debug("syncServiceInfo " + _tmp.toJSONString());
//TENTTHC
String tentthc = _tmp.getString("TENTTHC");
serviceInfo.setServiceName(tentthc);
//MATTHC
String matthc = _tmp.getString("MATTHC");
if ("sync".equalsIgnoreCase(type)) {
ServiceInfoMapping infoMapping = ServiceInfoMappingLocalServiceUtil.fetchByGID_SCDVCQG(groupId,
matthc);
if (infoMapping == null || Validator.isNull(infoMapping.getServiceCode())) {
return result;
}
matthc = infoMapping.getServiceCode();
}
serviceInfo.setServiceCode(matthc);
//TRINHTUTHUCHIEN
sb = new StringBuffer();
if (_tmp.has("TRINHTUTHUCHIEN")) {
JSONArray trinhtuthuchien_arr = _tmp.getJSONArray("TRINHTUTHUCHIEN");
if (trinhtuthuchien_arr != null) {
for (int i = 0; i < trinhtuthuchien_arr.length(); i++) {
JSONObject trinhtuthuchien_obj = trinhtuthuchien_arr.getJSONObject(i);
String truonghop = trinhtuthuchien_obj.getString("TRUONGHOP");
sb.append(truonghop + "<br>");
JSONArray trinhtu_arr = trinhtuthuchien_obj.getJSONArray("TRINHTU");
if (trinhtu_arr != null) {
for (int j = 0; j < trinhtu_arr.length(); j++) {
String tentrinhtu = trinhtu_arr.getJSONObject(j).getString("TENTRINHTU");
sb.append(tentrinhtu + "<br>");
}
}
}
}
}
serviceInfo.setProcessText(sb.toString());
//LINHVUCTHUCHIEN
String malinhvuc = StringPool.BLANK;
String tenlinhvuc = StringPool.BLANK;
if (_tmp.has("LINHVUCTHUCHIEN")) {
JSONArray linhvucthuchien_arr = _tmp.getJSONArray("LINHVUCTHUCHIEN");
if (linhvucthuchien_arr != null && linhvucthuchien_arr.length() > 0) {
JSONObject linhvucthuchien_obj = linhvucthuchien_arr.getJSONObject(0);
malinhvuc = linhvucthuchien_obj.getString("MALINHVUC");
tenlinhvuc = linhvucthuchien_obj.getString("TENLINHVUC");
}
}
if ("sync".equalsIgnoreCase(type)) {
DictItemMapping dictItemMapping = DictItemMappingLocalServiceUtil.fetchByF_GID_ICDVCQG_CID(groupId,
malinhvuc, domainCollectionId);
malinhvuc = dictItemMapping != null ? dictItemMapping.getItemCode() : StringPool.BLANK;
if (Validator.isNotNull(malinhvuc)) {
DictItem dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(malinhvuc,
domainCollectionId, groupId);
tenlinhvuc = dictItem != null ? dictItem.getItemName() : StringPool.BLANK;
}
}
serviceInfo.setDomainCode(malinhvuc);
serviceInfo.setDomainName(tenlinhvuc);
//MACOQUANCONGBO
String macoquancongbo = _tmp.getString("MACOQUANCONGBO");
String tencoquancongbo = StringPool.BLANK;
if ("sync".equalsIgnoreCase(type)) {
DictItemMapping dictItemMapping = DictItemMappingLocalServiceUtil.fetchByF_GID_ICDVCQG_CID(groupId,
macoquancongbo, govAgencyCollectionId);
macoquancongbo = dictItemMapping != null ? dictItemMapping.getItemCode() : StringPool.BLANK;
if (Validator.isNotNull(macoquancongbo)) {
DictItem dictItem = DictItemLocalServiceUtil.fetchByF_dictItemCode(macoquancongbo,
govAgencyCollectionId, groupId);
tencoquancongbo = dictItem != null ? dictItem.getItemName() : StringPool.BLANK;
}
}
serviceInfo.setAdministrationName(tencoquancongbo);
serviceInfo.setAdministrationCode(macoquancongbo);
//CACHTHUCTHUCHIEN
sb = new StringBuffer();
String durationText = StringPool.BLANK;
String feeText = StringPool.BLANK;
if (_tmp.has("CACHTHUCTHUCHIEN")) {
JSONArray cachthucthuchien_arr = _tmp.getJSONArray("CACHTHUCTHUCHIEN");
if (cachthucthuchien_arr != null) {
for (int i = 0; i < cachthucthuchien_arr.length(); i++) {
JSONObject cachthucthuchien_obj = cachthucthuchien_arr.getJSONObject(i);
int kenh = cachthucthuchien_obj.getInt("KENH");
String nhankenh = "Trực tiếp";
if (kenh == 2) {
nhankenh = "Trực tuyến";
} else if (kenh == 3) {
nhankenh = "Nộp qua bưu chính công ích";
}
sb.append(nhankenh + ":<br>");
JSONArray thoigian_arr = cachthucthuchien_obj.getJSONArray("THOIGIAN");
if (thoigian_arr != null) {
for (int j = 0; j < thoigian_arr.length(); j++) {
JSONObject thoigian_obj = thoigian_arr.getJSONObject(j);
int thoigiangiaiquyet = thoigian_obj.getInt("THOIGIANGIAIQUYET");
String donvitinh = thoigian_obj.getString("DONVITINH");
String mota = thoigian_obj.getString("MOTA");
sb.append("- Thời gian giải quyết: " + thoigiangiaiquyet + " " + donvitinh
+ (Validator.isNotNull(mota) ? "(" + mota + ")" : StringPool.BLANK)
+ "<br>");
durationText += nhankenh + ":" + "- Thời gian giải quyết: " + thoigiangiaiquyet
+ " " + donvitinh + "<br>";
JSONArray philephi_arr = thoigian_obj.getJSONArray("PHILEPHI");
if (philephi_arr != null && philephi_arr.length() > 0) {
String maphilephi = philephi_arr.getJSONObject(0).getString("MAPHILEPHI");
double sotien = philephi_arr.getJSONObject(0).getDouble("SOTIEN");
String donvi = philephi_arr.getJSONObject(0).getString("DONVI");
String lephimota = philephi_arr.getJSONObject(0).getString("MOTA");
feeText += nhankenh + ":" + maphilephi + ", " + sotien + " " + donvi
+ (Validator.isNotNull(lephimota) ? "(" + lephimota + ")"
: StringPool.BLANK)
+ "<br>";
}
}
}
}
}
}
serviceInfo.setMethodText(sb.toString());
//durationText
serviceInfo.setDurationText(durationText);
//feeText
serviceInfo.setFeeText(feeText);
//YEUCAU
String yeucau = StringPool.BLANK;
if (_tmp.has("YEUCAU")) {
yeucau = _tmp.getString("YEUCAU");
}
serviceInfo.setConditionText(yeucau);
//MOTADOITUONGTHUCHIEN
/*String motadoituongthuchien = StringPool.BLANK;
if (_tmp.has("MOTADOITUONGTHUCHIEN")) {
motadoituongthuchien = _tmp.getString("MOTADOITUONGTHUCHIEN");
_log.debug("MOTADOITUONGTHUCHIEN " + motadoituongthuchien);
}*/
//DOITUONGTHUCHIEN
sb = new StringBuffer();
if (_tmp.has("DOITUONGTHUCHIEN")) {
_log.debug("DOITUONGTHUCHIEN " + _tmp.getJSONArray("DOITUONGTHUCHIEN"));
JSONArray doituongthuchien_arr = _tmp.getJSONArray("DOITUONGTHUCHIEN");
if (doituongthuchien_arr != null) {
for (int i = 0; i < doituongthuchien_arr.length(); i++) {
JSONObject doituongthuchien_obj = doituongthuchien_arr.getJSONObject(i);
String doituongthuchien = doituongthuchien_obj.getString("TENDOITUONG");
sb.append(doituongthuchien + "<br>");
}
}
}
serviceInfo.setApplicantText(sb.toString());
//KETQUATHUCHIEN
sb = new StringBuffer();
if (_tmp.has("KETQUATHUCHIEN")) {
JSONArray ketquathuchien_arr = _tmp.getJSONArray("KETQUATHUCHIEN");
if (ketquathuchien_arr != null) {
for (int i = 0; i < ketquathuchien_arr.length(); i++) {
JSONObject ketquathuchien_obj = ketquathuchien_arr.getJSONObject(i);
String maketqua = ketquathuchien_obj.getString("MAKETQUA");
String tenketqua = ketquathuchien_obj.getString("TENKETQUA");
sb.append("- Mã kết quả:" + maketqua + "<br>");
sb.append("- Kết quả:" + tenketqua + "<br>");
}
}
}
serviceInfo.setResultText(sb.toString());
//CANCUPHAPLY
sb = new StringBuffer();
if (_tmp.has("CANCUPHAPLY")) {
JSONArray cancuphaply_arr = _tmp.getJSONArray("CANCUPHAPLY");
if (cancuphaply_arr != null) {
for (int i = 0; i < cancuphaply_arr.length(); i++) {
JSONObject cancuphaply_obj = cancuphaply_arr.getJSONObject(i);
String sovanban = cancuphaply_obj.getString("SOVANBAN");
String tenvanban = cancuphaply_obj.getString("TENVANBAN");
sb.append("- Số văn bản: " + sovanban + "<br>");
sb.append("- Tên văn bản: " + tenvanban + "<br>");
}
}
}
serviceInfo.setRegularText(sb.toString());
//TRANGTHAI
boolean public_ = true;
if (_tmp.has("TRANGTHAI")) {
int trangthai = _tmp.getInt("TRANGTHAI");
if (trangthai != 1) {
public_ = false;
}
}
serviceInfo.setPublic_(public_);
//COQUANTHUCHIEN
sb = new StringBuffer();
if (_tmp.has("COQUANTHUCHIEN")) {
JSONArray coquanthuchien_arr = _tmp.getJSONArray("COQUANTHUCHIEN");
if (coquanthuchien_arr != null) {
for (int i = 0; i < coquanthuchien_arr.length(); i++) {
JSONObject coquanthuchien_obj = coquanthuchien_arr.getJSONObject(i);
String tendonvi = coquanthuchien_obj.getString("TENDONVI");
String madonvi = coquanthuchien_obj.getString("MADONVI");
sb.append("- Tên đơn vị: " + tendonvi + "<br>");
sb.append("- Mã đơn vị: " + madonvi + "<br>");
}
}
}
serviceInfo.setGovAgencyText(sb.toString());
_log.debug("type " + type);
try {
if (type.equalsIgnoreCase("sync")) {
serviceInfo = ServiceInfoLocalServiceUtil.updateServiceInfo(serviceInfo);
_log.debug(serviceInfo.getApplicantText());
} else if (type.equalsIgnoreCase("create")) {
serviceInfo = ServiceInfoLocalServiceUtil.addServiceInfo(user.getUserId(), groupId,
serviceInfo.getServiceCode(), serviceInfo.getServiceName(),
serviceInfo.getProcessText(), serviceInfo.getMethodText(), serviceInfo.getDossierText(),
serviceInfo.getConditionText(), serviceInfo.getDurationText(),
serviceInfo.getApplicantText(), serviceInfo.getResultText(),
serviceInfo.getRegularText(), serviceInfo.getFeeText(),
serviceInfo.getAdministrationCode(), serviceInfo.getDomainCode(),
serviceInfo.getMaxLevel(), false, serviceInfo.getGovAgencyText(), serviceContext);
}
} catch (Exception e) {
_log.error(e);
result.put("serviceCode", serviceInfo.getServiceCode());
result.put("message", "error");
return result;
}
try {
//THANHPHANHOSO
List<ServiceFileTemplate> serviceFileTemplates = ServiceFileTemplateLocalServiceUtil
.getByServiceInfoId(serviceInfo.getServiceInfoId());
if (serviceFileTemplates != null) {
for (ServiceFileTemplate serviceFileTemplate : serviceFileTemplates) {
ServiceFileTemplateLocalServiceUtil.removeServiceFileTemplate(
serviceInfo.getServiceInfoId(), serviceFileTemplate.getFileTemplateNo());
}
}
if (_tmp.has("THANHPHANHOSO")) {
JSONArray thanhphanhoso_arr = _tmp.getJSONArray("THANHPHANHOSO");
ServiceInfoActions actions = new ServiceInfoActionsImpl();
if (thanhphanhoso_arr != null) {
for (int i = 0; i < thanhphanhoso_arr.length(); i++) {
JSONObject thanhphanhoso_obj = thanhphanhoso_arr.getJSONObject(i);
JSONArray giayto_arr = thanhphanhoso_obj.getJSONArray("GIAYTO");
if (giayto_arr != null) {
for (int j = 0; j < giayto_arr.length(); j++) {
JSONObject giayto_obj = giayto_arr.getJSONObject(j);
String magiayto = giayto_obj.getString("MAGIAYTO");
String tenmaudon = giayto_obj.getString("TENMAUDON");
String link = giayto_obj.getString("URL");
String tengiayto = giayto_obj.getString("TENGIAYTO");
if (Validator.isNotNull(link) && Validator.isNotNull(magiayto)) {
InputStream in = null;
URLConnection connection = null;
try {
URL url = new URL(link);
connection = url.openConnection();
in = connection.getInputStream();
String mimeType = URLConnection.guessContentTypeFromStream(in);
//String mimeType = MimeTypesUtil.getContentType(tenmaudon);
actions.addServiceFileTemplate(user.getUserId(),
serviceContext.getScopeGroupId(),
serviceInfo.getServiceInfoId(), magiayto, tengiayto, tenmaudon,
in, mimeType, connection.getContentLength(), serviceContext);
} catch (Exception e) {
_log.error(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e2) {
_log.error(e2);
}
}
}
}
}
}
}
}
}
} catch (Exception e) {
_log.error(e);
}
result.put("serviceCode", serviceInfo.getServiceCode());
result.put("message", "success");
return result;
} else {
result.put("serviceCode", serviceInfo.getServiceCode());
result.put("message", "error");
return result;
}
} else {
result.put("serviceCode", serviceInfo.getServiceCode());
result.put("message", "error");
return result;
}
}
public void syncFAQToDVCQG() {
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
//JSONObject result = JSONFactoryUtil.createJSONObject();
_log.info("-->>>>>>>> syncFAQToDVCQG: " + serverConfigs + "|" + serverConfigs.size());
if (serverConfigs != null && !serverConfigs.isEmpty()) {
ServerConfig serverConfig = serverConfigs.get(0);
try {
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
System.out.println(config.getLong("groupId"));
List<Question> questions = QuestionLocalServiceUtil.findByG_P_SYNC(config.getLong("groupId"), 1, 0);
_log.info("
if (questions != null) {
JSONArray data = JSONFactoryUtil.createJSONArray();
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "DongBoHoiDap");
JSONObject item = null;
for (Question question : questions) {
item = JSONFactoryUtil.createJSONObject();
item.put("HOIDAPID", question.getQuestionId());
item.put("MaLinhVuc", question.getDomainCode());
item.put("NOIDUNG", question.getContent());
item.put("MADONVI", question.getGovAgencyCode());
item.put("TENDONVI", question.getGovAgencyName());
//Answer answer = AnswerLocalServiceUtil.fi
//item.put("TRALOIID", question.getGovAgencyName());
//item.put("NOIDUNGTRALOI", question.getGovAgencyName());
data.put(item);
}
body.put("data", data);
JSONObject result = syncData(serverConfig, body);
if (result.has("error_code") && result.getInt("error_code") == 0) {
for (int i = 0; i < data.length(); i++) {
JSONObject _tmp = data.getJSONObject(i);
long questionId = _tmp.getLong("HOIDAPID");
Question question = QuestionLocalServiceUtil.fetchQuestion(questionId);
question.setSynced(1);
QuestionLocalServiceUtil.updateQuestion(question);
}
}
}
List<Answer> answers = AnswerLocalServiceUtil.findByG_P_SYNC(config.getLong("groupId"), 1, 0);
if (answers != null) {
JSONArray data = JSONFactoryUtil.createJSONArray();
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "DongBoKetQuaHoiDapGuiTuDVCQG");
JSONObject item = null;
for (Answer answer : answers) {
Question question = QuestionLocalServiceUtil.fetchQuestion(answer.getQuestionId());
if (question != null && question.getPublish() == 1
&& Validator.isNotNull(question.getClassName())
&& "dvcqg_question".contentEquals(question.getClassName())) {
item = JSONFactoryUtil.createJSONObject();
item.put("HOIDAPID", question.getClassPK());
item.put("MADONVI", question.getGovAgencyCode());
item.put("NGUOITRALOI", answer.getUserName());
item.put("CHUCVUNGUOITRALOI", "cb");
item.put("NGAYTRALOI", APIDateTimeUtils.convertDateToString(answer.getCreateDate(),
APIDateTimeUtils._NORMAL_DATE));
item.put("NOIDUNGTRALOI", answer.getContent());
data.put(item);
}
}
body.put("data", data);
JSONObject result = syncData(serverConfig, body);
/*if (result.has("error_code") && result.getInt("error_code") == 0) {
for (int i = 0; i < data.length(); i++) {
JSONObject _tmp = data.getJSONObject(i);
long questionId = _tmp.getLong("HOIDAPID");
Question question = QuestionLocalServiceUtil.fetchQuestion(questionId);
question.setSynced(1);
QuestionLocalServiceUtil.updateQuestion(question);
}
}*/
}
} catch (Exception e) {
_log.error(e);
}
}
}
@Override
public JSONObject doCreateDossierFromDVCQG(Company company, User user, long groupId, ServiceContext serviceContext,
JSONObject data) {
JSONObject result = JSONFactoryUtil.createJSONObject();
ServerConfig serverConfig = null;
List<ServerConfig> serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_INTEGRATION");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
serverConfig = serverConfigs.get(0);
}
if (serverConfig == null) {
return createResponseMessage(result, 404, "error",
"Not found server config width protocal: DVCQG_INTEGRATION");
}
if (data == null) {
return createResponseMessage(result, 500, "error", "Data empty");
}
String MaSoThue = data.getString("MaSoThue");
if (Validator.isNull(MaSoThue)) {
return createResponseMessage(result, 500, "error", "MaSoThue empty");
}
String techId = StringPool.BLANK;
JSONObject body = JSONFactoryUtil.createJSONObject();
body.put("service", "TraCuuTechID");
body.put("provider", "wso2is");
body.put("mstorcmnd", MaSoThue);
JSONObject searchObj = getSharingDictCollection(serverConfig, body);
_log.debug("Find TechId by MST " + searchObj.toJSONString());
if (searchObj != null && GetterUtil.getInteger(searchObj.getString("error_code")) == 0) {
JSONArray searchResultObj = searchObj.getJSONArray("result");
if (searchResultObj == null || searchResultObj.length() == 0) {
return createResponseMessage(result, 500, "error", "Can't get techId");
}
techId = searchResultObj.getJSONObject(0).getString("TECHNICALID");
if (Validator.isNull(techId)) {
return createResponseMessage(result, 500, "error", "Can't get techId");
}
} else {
return createResponseMessage(result, 500, "error", "Can't get techId");
}
String MaHoSo = data.getString("MaHoSo");
if (Validator.isNull(MaHoSo)) {
return createResponseMessage(result, 500, "error", "MaHoSo empty");
}
String MaTTHC = data.getString("MaTTHC");
ServiceInfoMapping mapping = ServiceInfoMappingLocalServiceUtil.fetchByGID_SCDVCQG(groupId, MaTTHC);
if (mapping == null) {
return createResponseMessage(result, 404, "error", "Not found serviceInfo mapping with: " + MaTTHC);
}
//String SoVanBan = data.getString("SoVanBan");
//String NgayNopHoSo = data.getString("NgayNopHoSo");
String TenThuongNhan = data.getString("TenThuongNhan");
JSONObject DiaChiDoanhNghiep_obj = data.getJSONObject("DiaChiDoanhNghiep");
String MaTinh = StringPool.BLANK;
String MaHuyen = StringPool.BLANK;
String MaXa = StringPool.BLANK;
String DiaChiChiTiet = StringPool.BLANK;
if (DiaChiDoanhNghiep_obj != null && DiaChiDoanhNghiep_obj.length() > 0) {
MaTinh = DiaChiDoanhNghiep_obj.getString("MaTinh");
MaHuyen = DiaChiDoanhNghiep_obj.getString("MaHuyen");
MaXa = DiaChiDoanhNghiep_obj.getString("MaXa");
DiaChiChiTiet = DiaChiDoanhNghiep_obj.getString("DiaChiChiTiet");
}
String DienThoai = data.getString("DienThoai");
//String Fax = data.getString("Fax");
String Email = data.getString("Email");
String NguoiLienHe = data.getString("NguoiLienHe");
//String SoDienThoaiNguoiLienHe = data.getString("SoDienThoaiNguoiLienHe");
String TenChuongTrinhKhuyenMai = data.getString("TenChuongTrinhKhuyenMai");
//String HinhThucKhuyenMai = data.getString("HinhThucKhuyenMai");
//String ThoiGianKhuyenMaiTu = data.getString("ThoiGianKhuyenMaiTu");
//String ThoiGianKhuyenMaiDen = data.getString("ThoiGianKhuyenMaiDen");
//String HangHoaDichVuKhuyenMai = data.getString("HangHoaDichVuKhuyenMai");
//String SoLuongHangHoaDichVu = data.getString("SoLuongHangHoaDichVu");
//String KhachHang = data.getString("KhachHang");
//String CoCauGiaiThuong = data.getString("CoCauGiaiThuong");
//String TongGiaTriHangHoa = data.getString("TongGiaTriHangHoa");
//String NoiDungChiTiet = data.getString("NoiDungChiTiet");
//String TenCacThuongNhanCungThucHien = data.getString("TenCacThuongNhanCungThucHien");
String TenTepDonDangKy = data.getString("TenTepDonDangKy");
String TepDonDangKy = data.getString("TepDonDangKy");//base64
//find applicant
Applicant applicant = ApplicantLocalServiceUtil.fetchByF_APLC_GID(groupId, MaSoThue);
if (applicant != null && Validator.isNull(applicant.getMappingClassPK())) {
try {
applicant = ApplicantLocalServiceUtil.updateApplication(serviceContext, groupId,
applicant.getApplicantId(), _DEFAULT_CLASS_NAME, techId);
} catch (Exception e) {
_log.error(e);
return createResponseMessage(result, 500, "error", "Can't update applicant mappingClassPK");
}
} else if (applicant == null) {
try {
String cityName = StringPool.BLANK;
String districtName = StringPool.BLANK;
String wardName = StringPool.BLANK;
applicant = ApplicantLocalServiceUtil.updateApplication(serviceContext, groupId, 0L, TenThuongNhan,
"business", MaSoThue, DateTimeUtils.dateToString(new Date(), DateTimeUtils._TYPEDATE),
DiaChiChiTiet, MaTinh, cityName, MaHuyen, districtName, MaXa, wardName, NguoiLienHe, DienThoai,
Email, StringPool.BLANK, StringPool.BLANK, true);
applicant = ApplicantLocalServiceUtil.updateApplication(serviceContext, groupId,
applicant.getApplicantId(), _DEFAULT_CLASS_NAME, techId);
} catch (Exception e) {
_log.error(e);
return createResponseMessage(result, 500, "error", "Can't create applicant");
}
}
//create dossier
try {
serverConfig = null;
serverConfigs = ServerConfigLocalServiceUtil.getByProtocol("DVCQG_TTKM");
if (serverConfigs != null && !serverConfigs.isEmpty()) {
serverConfig = serverConfigs.get(0);
_log.debug("serverConfig " + serverConfig);
}
if (serverConfig == null) {
return createResponseMessage(result, 404, "error",
"Not found server config width protocal: DVCQG_TTKM");
}
JSONObject config = JSONFactoryUtil.createJSONObject(serverConfig.getConfigs());
//String serverNo = config.getString("serverNo");
String serviceCode = config.getString("serviceCode");
String govAgencyCode = config.getString("govAgencyCode");
String dossierTemplateNo = config.getString("dossierTemplateNo");
String actionCode = config.getString("actionCode");
ActionConfig actConfig = ActionConfigLocalServiceUtil.getByCode(groupId, actionCode);
if (actConfig == null) {
return createResponseMessage(result, 404, "error", "Not found ActionConfig");
}
DossierInputModel inputModel = new DossierInputModel();
inputModel.setServiceCode(serviceCode);
inputModel.setGovAgencyCode(govAgencyCode);
inputModel.setDossierTemplateNo(dossierTemplateNo);
inputModel.setOriginality(String.valueOf(1));
inputModel.setApplicantName(applicant.getApplicantName());
inputModel.setDossierNo(StringPool.BLANK);
inputModel.setApplicantIdType(applicant.getApplicantIdType());
inputModel.setApplicantIdNo(applicant.getApplicantIdNo());
inputModel.setAddress(applicant.getAddress());
inputModel.setCityCode(applicant.getCityCode());
inputModel.setDistrictCode(applicant.getDistrictCode());
inputModel.setWardCode(applicant.getWardCode());
inputModel.setContactTelNo(applicant.getContactTelNo());
inputModel.setContactEmail(applicant.getContactEmail());
inputModel.setDelegateName(applicant.getApplicantName());
inputModel.setDelegateIdNo(applicant.getApplicantIdNo());
inputModel.setDelegateTelNo(applicant.getContactTelNo());
inputModel.setDelegateEmail(applicant.getContactEmail());
inputModel.setDelegateAddress(applicant.getAddress());
inputModel.setDelegateCityCode(applicant.getCityCode());
inputModel.setDelegateDistrictCode(applicant.getDistrictCode());
inputModel.setDelegateWardCode(applicant.getWardCode());
inputModel.setApplicantNote(StringPool.BLANK);
inputModel.setSameAsApplicant(false);
inputModel.setSampleCount(0L);
inputModel.setDossierNo(MaHoSo);
inputModel.setDossierName(TenChuongTrinhKhuyenMai);
//inputModel.setMetaData(metaData);
Dossier dossier = CPSDossierBusinessLocalServiceUtil.addDossier(groupId, company, user, serviceContext,
inputModel);
_log.debug(JSONFactoryUtil.looseSerialize(dossier));
//update file
addDossierFileAttachment(groupId, dossier.getDossierId(), dossierTemplateNo, TenTepDonDangKy, TepDonDangKy,
serviceContext);
JSONArray TaiLieuNop_arr = data.getJSONArray("TaiLieuNop");
if (TaiLieuNop_arr != null && TaiLieuNop_arr.length() > 0) {
for (int i = 0; i < TaiLieuNop_arr.length(); i++) {
JSONObject TaiLieuNop_obj = TaiLieuNop_arr.getJSONObject(i);
String TenTepDinhKem = TaiLieuNop_obj.getString("TenTepDinhKem");
String Base64 = TaiLieuNop_obj.getString("Base64");
addDossierFileAttachment(groupId, dossier.getDossierId(), dossierTemplateNo, TenTepDinhKem, Base64,
serviceContext);
}
}
//post action
DossierActions actions = new DossierActionsImpl();
ProcessOption option = getProcessOption(serviceCode, govAgencyCode, dossierTemplateNo, groupId);
ErrorMsgModel errorModel = new ErrorMsgModel();
actions.doAction(groupId, applicant.getMappingUserId(), dossier, option, null, actionCode,
applicant.getApplicantName(), StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
StringPool.BLANK, actConfig.getSyncType(), serviceContext, errorModel);
return createResponseMessage(result, 200, "success", "create dossier success");
} catch (Exception e) {
_log.error(e);
return createResponseMessage(result, 500, "error", "create dossier error");
}
}
private ProcessOption getProcessOption(String serviceInfoCode, String govAgencyCode, String dossierTemplateNo,
long groupId) throws PortalException {
ServiceConfig config = ServiceConfigLocalServiceUtil.getBySICodeAndGAC(groupId, serviceInfoCode, govAgencyCode);
if (config != null) {
return ProcessOptionLocalServiceUtil.getByDTPLNoAndServiceCF(groupId, dossierTemplateNo,
config.getServiceConfigId());
} else {
return null;
}
}
private void addDossierFileAttachment(long groupId, long dossierId, String dossierTemplateNo, String fileName,
String base64, ServiceContext serviceContext) throws PortalException, IOException {
if (Validator.isNotNull(fileName) && Validator.isNotNull(base64)) {
DossierPart dossierPart = DossierPartLocalServiceUtil.fetchByTemplatePartNo(groupId, dossierTemplateNo,
"TP99");
String fileTemplateNo = StringPool.BLANK;
if (dossierPart != null) {
fileTemplateNo = dossierPart.getFileTemplateNo();
}
String referenceUid = StringPool.BLANK;
File file = DossierFileUtils.base64ToFile(fileName, base64);
InputStream inputStream = DossierFileUtils.fileToInputStream(file);
JSONObject fileMetadata = DossierFileUtils.getFileMetadata(file);
if (inputStream != null) {
DossierFile dossierFile = DossierFileLocalServiceUtil.addDossierFile(groupId, dossierId, referenceUid,
dossierTemplateNo, "TP99", fileTemplateNo, fileName, fileName, fileMetadata.getLong("fileSize"),
inputStream, fileMetadata.getString("mimeType"), String.valueOf(false), serviceContext);
_log.debug("Attachment dossierFile " + fileName + " " + JSONFactoryUtil.looseSerialize(dossierFile));
}
}
}
private JSONObject createResponseMessage(JSONObject object, int status, String message, String desc) {
object.put("status", status);
object.put("message", message);
object.put("description", desc);
return object;
}
private String _DEFAULT_CLASS_NAME = "dvcqg";
}
|
package osgi.enroute.trains.train.manager.example.provider;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import osgi.enroute.scheduler.api.Scheduler;
import osgi.enroute.trains.cloud.api.Observation;
import osgi.enroute.trains.cloud.api.TrackForTrain;
import osgi.enroute.trains.track.util.Tracks;
import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
import osgi.enroute.trains.train.api.TrainController;
import osgi.enroute.trains.train.manager.example.provider.ExampleTrainManagerImpl.Config;
/**
* Train manager.
*/
@Designate(ocd = Config.class, factory = true)
@Component(name = Config.TRAIN_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE,
immediate = true, service = Object.class)
public class ExampleTrainManagerImpl {
@ObjectClassDefinition
@interface Config {
final static public String TRAIN_CONFIG_PID = "osgi.enroute.trains.train.manager";
String name();
String rfid();
int speed() default 50;
String TrainController_target();
}
static Logger logger = LoggerFactory.getLogger(ExampleTrainManagerImpl.class);
TrainController trainController;
// TrainController.target is set in config
@Reference(name = "TrainController")
void setTrainController(TrainController trainCtrl) {
trainController = trainCtrl;
}
@Reference
private TrackForTrain trackManager;
@Reference
private Scheduler scheduler;
private Tracks<Object> tracks;
private String name;
private String rfid;
private int speed;
private int lastMove = 0;
private Thread mgmtThread;
@Activate
public void activate(Config config) throws Exception {
name = config.name();
rfid = config.rfid();
speed = config.speed();
info("activate: speed<{}> rfid<{}>", speed, rfid);
// register train with Track Manager
trackManager.registerTrain(name, rfid);
// create Track
tracks = new Tracks<Object>(trackManager.getSegments().values(), new TrainManagerFactory());
mgmtThread = new Thread(new TrainMgmtLoop());
mgmtThread.start();
}
@Deactivate
public void deactivate() {
info("deactivate");
try {
mgmtThread.interrupt();
mgmtThread.join(5000);
} catch (InterruptedException e) {
}
// stop when deactivated
stop();
}
private void move(int moveSpeed) {
if (lastMove != moveSpeed || moveSpeed == 0) {
info("move({})", moveSpeed);
lastMove = moveSpeed;
trainController.move(moveSpeed);
}
}
private void stop() {
move(0);
light(false);
}
private void light(boolean on) {
trainController.light(on);
}
private class TrainMgmtLoop implements Runnable {
private String currentAssignment = null;
private String currentLocation = null;
private String currentAccess = null;
private LinkedList<SegmentHandler<Object>> route = null;
private void abort() {
stop();
currentAssignment = null;
route = null;
}
@Override
public void run() {
// get observations, without blocking, to find lastObservation
// and to avoid re-processing same observations on restart
List<Observation> observations = trackManager.getRecentObservations(-2);
long lastObsId = -1;
boolean blocked = false;
if (!observations.isEmpty()) {
Observation lastObs = observations.get(observations.size() - 1);
lastObsId = lastObs.id;
info("disgard old observations: last: {}", lastObs);
}
stop();
while (isActive()) {
observations = trackManager
.getRecentObservations(lastObsId - (blocked ? 1 : 0));
if (blocked && observations.size() > 1) {
// remove the observation that caused block and process next
// otherwise re-process previous observation, which should
// drop back to followRoute()
observations.remove(0);
blocked = false;
}
for (Observation o : observations) {
lastObsId = o.id;
tracks.event(o);
if (name == null || !name.equals(o.train)) {
continue;
}
switch (o.type) {
case ASSIGNMENT:
// new assignment, plan and follow the route
info("New Assignment<{}>", o.assignment);
currentAssignment = o.assignment;
if (currentLocation == null) {
info("start moving to find location");
move(speed);
} else {
planRoute();
blocked = followRoute();
}
break;
case LOCATED:
info("Located @ {}", o.segment);
if (currentLocation == null && currentAssignment != null) {
currentLocation = o.segment;
move(0);
planRoute();
} else {
currentLocation = o.segment;
}
// stop when assignment reached
if (currentAssignment == null) {
info("Waiting for an assignment");
stop();
} else if (currentAssignment.equals(currentLocation)) {
info("Reached assignment<{}>", currentAssignment);
currentAssignment = null;
stop();
blink(3);
trackManager.assignmentReached(name, currentLocation);
} else {
blocked = followRoute();
}
break;
case BLOCKED:
case CHANGE:
case SIGNAL:
case SWITCH:
case TIMEOUT:
default:
break;
}
}
}
info("management loop terminated.");
}
private void blink(int n) {
light(false);
if (n > 0) {
scheduler.after(() -> {
light(true);
scheduler.after(() -> blink(n - 1), 500);
}, 500);
}
}
private void planRoute() {
if (currentLocation == null)
return;
if (currentAssignment == null)
return;
// plan the route
SegmentHandler<Object> src = tracks.getHandler(currentLocation);
SegmentHandler<Object> dest = tracks.getHandler(currentAssignment);
route = src.findForward(dest);
}
private boolean followRoute() {
if (route == null || route.isEmpty())
return false;
light(true);
Optional<SegmentHandler<Object>> mySegment = route.stream()
.filter(sh -> sh.segment.id.equals(currentLocation))
.findFirst();
if (!mySegment.isPresent()) {
error("location<{}> is not on route. stop.", currentLocation);
abort();
return false;
}
Optional<SegmentHandler<Object>> nextLocator;
String fromTrack;
String toTrack;
// update the remaining part of the current route
while (route.size() > 0 && !route.getFirst().segment.id.equals(currentLocation)) {
SegmentHandler<Object> removed = route.removeFirst();
if (removed.isLocator()) {
info("eek! missed locator <{}>", removed.segment.id);
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (nextLocator.isPresent()) {
fromTrack = removed.getTrack();
toTrack = nextLocator.get().getTrack();
if (!fromTrack.equals(toTrack)) {
info("retrospectively request access to <{}> from <{}>", toTrack, fromTrack);
move(0);
requestAccess(fromTrack, toTrack);
}
}
}
}
// figure out where to go to next
fromTrack = route.removeFirst().getTrack();
// check if we have to go to a new track before we have a new
// Locator
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (!nextLocator.isPresent()) {
error("no locator to go to, stop now");
abort();
return false;
}
toTrack = nextLocator.get().getTrack();
// if we have to go to other track, request access
if (!fromTrack.equals(toTrack) && !toTrack.equals(currentAccess)) {
info("stop and request access to track<{}> from <{}>", toTrack, currentLocation);
move(0);
boolean granted = false;
// simply keep on trying until access is given
while (!granted && isActive()) {
granted = requestAccess(fromTrack, toTrack);
if (!granted) {
// allow mgmt loop to process other events
// return true;
}
}
}
// just go forward
move(speed);
return false;
}
private boolean requestAccess(String fromTrack, String toTrack) {
boolean granted = false;
try {
granted = trackManager.requestAccessTo(name, fromTrack, toTrack);
} catch (Exception e) {
error("request access failed: " + e);
abort();
}
info("access is {}", granted ? "granted" : "blocked");
currentAccess = (granted ? toTrack : null);
return granted;
}
private boolean isActive() {
return !Thread.currentThread().isInterrupted();
}
}
private void info(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.out.printf(ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
}
private void error(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.err.printf("ERROR: " + ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
logger.error(ident + fmt, args);
}
}
|
package com.matthewtamlin.spyglass.processors.annotation_utils.default_annotation_util;
import com.google.testing.compile.JavaFileObjects;
import com.matthewtamlin.java_compiler_utilities.element_supplier.CompilerMissingException;
import com.matthewtamlin.java_compiler_utilities.element_supplier.IdBasedElementSupplier;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.File;
import java.lang.annotation.Annotation;
import java.net.MalformedURLException;
import javax.lang.model.element.Element;
import javax.tools.JavaFileObject;
import static com.matthewtamlin.spyglass.annotations.units.DimensionUnit.DP;
import static com.matthewtamlin.spyglass.processors.annotation_utils.DefaultAnnotationUtil.getDefaultAnnotation;
import static com.matthewtamlin.spyglass.processors.annotation_utils.DefaultAnnotationUtil.hasDefaultAnnotation;
import static com.matthewtamlin.spyglass.processors.annotation_utils.DefaultAnnotationUtil.isDefaultAnnotation;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockBooleanHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockColorHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockColorStateListHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToBoolean;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToBooleanResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToColorResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToColorStateListResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToDimension;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToDimensionResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToDrawableResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToEnumConstant;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToFloat;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToFractionResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToInteger;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToIntegerResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToNull;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToString;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToStringResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToTextArrayResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDefaultToTextResource;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDimensionHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockDrawableHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockEnumConstantHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockEnumOrdinalHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockFloatHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockFractionHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockIntegerHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockSpecificEnumHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockSpecificFlagHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockStringHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockTextArrayHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockTextHandler;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseBoolean;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseByte;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseChar;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseDouble;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseFloat;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseInt;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseLong;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseNull;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseShort;
import static com.matthewtamlin.spyglass.processors.testing_utils.MockAnnotationsSupplier.createMockUseString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@RunWith(JUnit4.class)
public class TestDefaultAnnotationUtil {
private static final File DATA_FILE = new File("processors/src/test/java/com/matthewtamlin/spyglass/processors" +
"/annotation_utils/default_annotation_util/Data.java");
private Element withDefaultToBoolean;
private Element withDefaultToBooleanResource;
private Element withDefaultToColorResource;
private Element withDefaultToColorStateListResource;
private Element withDefaultToDimension;
private Element withDefaultToDimensionResource;
private Element withDefaultToDrawableResource;
private Element withDefaultToEnumConstant;
private Element withDefaultToFloat;
private Element withDefaultToFractionResource;
private Element withDefaultToInteger;
private Element withDefaultToIntegerResource;
private Element withDefaultToNull;
private Element withDefaultToString;
private Element withDefaultToStringResource;
private Element withDefaultToTextArrayResource;
private Element withDefaultToTextResource;
private Element withNoDefaultAnnotation;
@Before
public void setup() throws MalformedURLException, CompilerMissingException {
assertThat("Data file does not exist.", DATA_FILE.exists(), is(true));
final JavaFileObject dataFileObject = JavaFileObjects.forResource(DATA_FILE.toURI().toURL());
final IdBasedElementSupplier elementSupplier = new IdBasedElementSupplier(dataFileObject);
withDefaultToBoolean = elementSupplier.getUniqueElementWithId("boolean");
withDefaultToBooleanResource = elementSupplier.getUniqueElementWithId("boolean resource");
withDefaultToColorResource = elementSupplier.getUniqueElementWithId("color resource");
withDefaultToColorStateListResource = elementSupplier.getUniqueElementWithId("color state list resource");
withDefaultToDimension = elementSupplier.getUniqueElementWithId("dimension");
withDefaultToDimensionResource = elementSupplier.getUniqueElementWithId("dimension resource");
withDefaultToDrawableResource = elementSupplier.getUniqueElementWithId("drawable resource");
withDefaultToEnumConstant = elementSupplier.getUniqueElementWithId("enum constant");
withDefaultToFloat = elementSupplier.getUniqueElementWithId("float");
withDefaultToFractionResource = elementSupplier.getUniqueElementWithId("fraction resource");
withDefaultToInteger = elementSupplier.getUniqueElementWithId("integer");
withDefaultToIntegerResource = elementSupplier.getUniqueElementWithId("integer resource");
withDefaultToNull = elementSupplier.getUniqueElementWithId("null");
withDefaultToString = elementSupplier.getUniqueElementWithId("string");
withDefaultToStringResource = elementSupplier.getUniqueElementWithId("string resource");
withDefaultToTextArrayResource = elementSupplier.getUniqueElementWithId("text array resource");
withDefaultToTextResource = elementSupplier.getUniqueElementWithId("text resource");
withNoDefaultAnnotation = elementSupplier.getUniqueElementWithId("no default annotation");
}
@Test(expected = IllegalArgumentException.class)
public void testGetDefaultAnnotation_nullSupplied() {
getDefaultAnnotation(null);
}
@Test
public void testGetDefaultAnnotation_defaultToBooleanAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToBoolean);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToBooleanResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToBooleanResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToColorResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToColorResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToColorStateListResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToColorStateListResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToDimensionAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToDimension);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToDimensionResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToDimensionResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToDrawableResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToDrawableResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToEnumConstantAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToEnumConstant);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToFloatAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToFloat);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToFractionResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToFractionResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToIntegerAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToInteger);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToIntegerResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToIntegerResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToNullAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToNull);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToStringAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToString);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToStringResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToStringResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToTextArrayResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToTextArrayResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_defaultToTextResourceAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withDefaultToTextResource);
assertThat(anno, is(notNullValue()));
}
@Test
public void testGetDefaultAnnotation_noDefaultAnnotationPresent() {
final Annotation anno = getDefaultAnnotation(withNoDefaultAnnotation);
assertThat(anno, is(nullValue()));
}
@Test(expected = IllegalArgumentException.class)
public void testIsDefaultAnnotation_nullSupplied() {
isDefaultAnnotation(null);
}
@Test
public void testIsDefaultAnnotation_specificEnumHandlerAnnotationSupplied() {
final Annotation a = createMockSpecificEnumHandler(0, 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_specificFlagHandlerAnnotationSupplied() {
final Annotation a = createMockSpecificFlagHandler(0, 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_defaultToBooleanAnnotationSupplied() {
final Annotation a = createMockDefaultToBoolean(true);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToBooleanResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToBooleanResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToColorResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToColorResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToColorStateListResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToColorStateListResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToDimensionAnnotationSupplied() {
final Annotation a = createMockDefaultToDimension(0, DP);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToDimensionResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToDimensionResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToDrawableResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToDrawableResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToEnumConstantAnnotationSupplied() {
final Annotation a = createMockDefaultToEnumConstant(PlaceholderEnum.class, 0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToFloatAnnotationSupplied() {
final Annotation a = createMockDefaultToFloat(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToFractionResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToFractionResource(0, 0, 0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToIntegerAnnotationSupplied() {
final Annotation a = createMockDefaultToInteger(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToIntegerResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToIntegerResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToNullAnnotationSupplied() {
final Annotation a = createMockDefaultToNull();
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToStringAnnotationSupplied() {
final Annotation a = createMockDefaultToString("hello world");
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToStringResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToStringResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToTextArrayResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToTextArrayResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_defaultToTextResourceAnnotationSupplied() {
final Annotation a = createMockDefaultToTextResource(0);
assertThat(isDefaultAnnotation(a), is(true));
}
@Test
public void testIsDefaultAnnotation_useBooleanAnnotationSupplied() {
final Annotation a = createMockUseBoolean(true);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useByteAnnotationSupplied() {
final Annotation a = createMockUseByte((byte) 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useCharAnnotationSupplied() {
final Annotation a = createMockUseChar((char) 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useDoubleAnnotationSupplied() {
final Annotation a = createMockUseDouble(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useFloatAnnotationSupplied() {
final Annotation a = createMockUseFloat(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useIntAnnotationSupplied() {
final Annotation a = createMockUseInt(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useLongAnnotationSupplied() {
final Annotation a = createMockUseLong(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useNullAnnotationSupplied() {
final Annotation a = createMockUseNull();
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useShortAnnotationSupplied() {
final Annotation a = createMockUseShort((short) 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_useStringAnnotationSupplied() {
final Annotation a = createMockUseString("hello world");
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_booleanHandlerAnnotationSupplied() {
final Annotation a = createMockBooleanHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_colorHandlerAnnotationSupplied() {
final Annotation a = createMockColorHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_colorStateListHandlerAnnotationSupplied() {
final Annotation a = createMockColorStateListHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_dimensionHandlerAnnotationSupplied() {
final Annotation a = createMockDimensionHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_drawableHandlerAnnotationSupplied() {
final Annotation a = createMockDrawableHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_enumConstantHandlerAnnotationSupplied() {
final Annotation a = createMockEnumConstantHandler(0, PlaceholderEnum.class);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_enumOrdinalHandlerAnnotationSupplied() {
final Annotation a = createMockEnumOrdinalHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_floatHandlerAnnotationSupplied() {
final Annotation a = createMockFloatHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_fractionHandlerAnnotationSupplied() {
final Annotation a = createMockFractionHandler(0, 0, 0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_integerHandlerAnnotationSupplied() {
final Annotation a = createMockIntegerHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_stringHandlerAnnotationSupplied() {
final Annotation a = createMockStringHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_textArrayHandlerAnnotationSupplied() {
final Annotation a = createMockTextArrayHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test
public void testIsDefaultAnnotation_textHandlerAnnotationSupplied() {
final Annotation a = createMockTextHandler(0);
assertThat(isDefaultAnnotation(a), is(false));
}
@Test(expected = IllegalArgumentException.class)
public void testHasDefaultAnnotation_nullSupplied() {
hasDefaultAnnotation(null);
}
@Test
public void testHasDefaultAnnotation_defaultToBooleanAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToBoolean);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToBooleanResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToBooleanResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToColorResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToColorResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToColorStateListResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToColorStateListResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToDimensionAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToDimension);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToDimensionResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToDimensionResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToDrawableResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToDrawableResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToEnumConstantAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToEnumConstant);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToFloatAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToFloat);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToFractionResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToFractionResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToIntegerAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToInteger);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToIntegerResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToIntegerResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToNullAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToNull);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToStringAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToString);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToStringResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToStringResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToTextArrayResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToTextArrayResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_defaultToTextResourceAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withDefaultToTextResource);
assertThat(hasHandler, is(true));
}
@Test
public void testHasDefaultAnnotation_noDefaultAnnotationPresent() {
final boolean hasHandler = hasDefaultAnnotation(withNoDefaultAnnotation);
assertThat(hasHandler, is(false));
}
private enum PlaceholderEnum {}
}
|
package org.csstudio.archive.reader.appliance;
import java.util.concurrent.ConcurrentHashMap;
import org.csstudio.archive.reader.ArchiveReader;
import org.csstudio.archive.reader.ArchiveReaderFactory;
/**
* Provides instance of the appliance archive reader.
*
* @author Miha Novak <miha.novak@cosylab.com>
*/
public class ApplianceArchiveReaderFactory implements ArchiveReaderFactory{
/* (non-Javadoc)
* @see org.csstudio.archive.reader.ArchiveReaderFactory#getArchiveReader(java.lang.String)
*/
final private static ConcurrentHashMap<String, ApplianceArchiveReader> cache = new ConcurrentHashMap<String, ApplianceArchiveReader>();
@Override
public ArchiveReader getArchiveReader(String url) throws Exception {
ApplianceArchiveReader result = cache.get(url);
if( result == null ) {
final ApplianceArchiveReader reader = new ApplianceArchiveReader(url, Activator.getDefault().isUseStatistics());
result = cache.putIfAbsent(url, reader);
if( result == null ) {
result = reader;
}
}
return result;
}
}
|
//$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/deegree3/trunk/deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/iso/persistence/QueryHelper.java $
package org.deegree.metadata.iso.persistence.sql;
import static org.deegree.commons.jdbc.ConnectionManager.Type.MSSQL;
import static org.deegree.commons.jdbc.ConnectionManager.Type.Oracle;
import static org.deegree.commons.jdbc.ConnectionManager.Type.PostgreSQL;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.deegree.commons.utils.JDBCUtils;
import org.deegree.commons.utils.StringUtils;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.OperatorFilter;
import org.deegree.metadata.i18n.Messages;
import org.deegree.metadata.iso.persistence.ISOMetadataResultSet;
import org.deegree.metadata.iso.persistence.ISOPropertyNameMapper;
import org.deegree.metadata.iso.persistence.queryable.Queryable;
import org.deegree.metadata.persistence.MetadataQuery;
import org.deegree.protocol.csw.CSWConstants.ResultType;
import org.deegree.protocol.csw.MetadataStoreException;
import org.deegree.sqldialect.SQLDialect;
import org.deegree.sqldialect.filter.AbstractWhereBuilder;
import org.deegree.sqldialect.filter.UnmappableException;
import org.deegree.sqldialect.filter.expression.SQLArgument;
import org.slf4j.Logger;
public class DefaultQueryService extends AbstractSqlHelper implements QueryService {
private static final Logger LOG = getLogger( DefaultQueryService.class );
/** Used to limit the fetch size for SELECT statements that potentially return a lot of rows. */
private static final int DEFAULT_FETCH_SIZE = 100;
private static final int QUERY_TIMEOUT_MS = 300000;
public DefaultQueryService( SQLDialect dialect, List<Queryable> queryables ) {
super( dialect, queryables );
}
@Override
public ISOMetadataResultSet execute( MetadataQuery query, Connection conn )
throws MetadataStoreException {
ResultSet rs = null;
PreparedStatement preparedStatement = null;
try {
AbstractWhereBuilder builder = getWhereBuilder( query, conn );
StringBuilder idSelect = getPreparedStatementDatasetIDs( builder );
// TODO: use SQLDialect
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == MSSQL ) {
String oldHeader = idSelect.toString();
idSelect = idSelect.append( " from (" ).append( oldHeader );
idSelect.append( ", ROW_NUMBER() OVER (ORDER BY X1.ID) as rownum" );
}
if ( query != null && ( query.getStartPosition() != 1 || query.getMaxRecords() > -1 )
&& dialect.getDBType() == Oracle ) {
String oldHeader = idSelect.toString();
idSelect = new StringBuilder();
idSelect.append( "select * from ( " );
if ( query.getStartPosition() != 1 ) {
idSelect.append( "select a.*, ROWNUM rnum from (" );
}
idSelect.append( oldHeader );
}
getPSBody( builder, idSelect );
if ( builder.getOrderBy() != null ) {
idSelect.append( " ORDER BY " );
idSelect.append( builder.getOrderBy().getSQL() );
}
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == PostgreSQL ) {
idSelect.append( " OFFSET " ).append( Integer.toString( query.getStartPosition() - 1 ) );
}
if ( query != null && query.getStartPosition() != 1 && dialect.getDBType() == MSSQL ) {
idSelect.append( ") as X1 where X1.rownum > " );
idSelect.append( query.getStartPosition() - 1 );
}
// take a look in the wiki before changing this!
if ( dialect.getDBType() == PostgreSQL && query != null && query.getMaxRecords() > -1 ) {
idSelect.append( " LIMIT " ).append( query.getMaxRecords() );
}
if ( query != null && ( query.getStartPosition() != 1 || query.getMaxRecords() > -1 )
&& dialect.getDBType() == Oracle ) {
idSelect.append( " ) " );
if ( query.getStartPosition() != 1 ) {
idSelect.append( " a " );
}
if ( query.getMaxRecords() > -1 ) {
int max = query.getMaxRecords() - 1;
if ( query.getStartPosition() != -1 ) {
max += query.getStartPosition();
}
idSelect.append( " WHERE ROWNUM <= " ).append( max );
}
if ( query.getStartPosition() != 1 ) {
int min = query.getStartPosition();
idSelect.append( " ) WHERE rnum >= " ).append( min );
}
}
StringBuilder outerSelect = new StringBuilder( "SELECT " );
outerSelect.append( recordColumn );
outerSelect.append( " FROM " );
outerSelect.append( ISOPropertyNameMapper.DatabaseTables.idxtb_main );
outerSelect.append( " A INNER JOIN (" );
outerSelect.append( idSelect );
outerSelect.append( ") B ON A.id=B.id" );
// append sort criteria in the outer again, because IN statement looses ordering from inner ORDER BY
if ( builder.getOrderBy() != null ) {
outerSelect.append( " ORDER BY " );
// check that all sort columns belong to root table
String sortCols = builder.getOrderBy().getSQL().toString();
String rootTableQualifier = builder.getAliasManager().getRootTableAlias() + ".";
int columnCount = StringUtils.count( sortCols, "," ) + 1;
int rootAliasCount = StringUtils.count( sortCols, rootTableQualifier );
if ( rootAliasCount < columnCount ) {
String msg = "Sorting based on properties not stored in the root table is currently not supported.";
throw new MetadataStoreException( msg );
}
String colRegEx = builder.getAliasManager().getRootTableAlias() + ".\\S+";
for ( int i = 1; i <= columnCount; i++ ) {
sortCols = sortCols.replaceFirst( colRegEx, "crit" + i );
}
outerSelect.append( sortCols );
}
String sql = outerSelect.toString();
LOG.trace( sql );
preparedStatement = createPreparedStatement( conn, sql );
int i = 1;
if ( builder.getWhere() != null ) {
for ( SQLArgument o : builder.getWhere().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
if ( builder.getOrderBy() != null ) {
for ( SQLArgument o : builder.getOrderBy().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
LOG.debug( preparedStatement.toString() );
preparedStatement.setFetchSize( DEFAULT_FETCH_SIZE );
rs = preparedStatement.executeQuery();
return new ISOMetadataResultSet( rs, conn, preparedStatement );
} catch ( SQLException e ) {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
String msg = Messages.getMessage( "ERROR_SQL", preparedStatement.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} catch ( Throwable t ) {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
String msg = Messages.getMessage( "ERROR_REQUEST_TYPE", ResultType.results.name(), t.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
// Don't close the ResultSet or PreparedStatement if no error occurs, the ResultSet is needed in the
// ISOMetadataResultSet and both will be closed by
// org.deegree.metadata.persistence.XMLMetadataResultSet#close().
}
}
@Override
public int executeCounting( MetadataQuery query, Connection conn )
throws MetadataStoreException, FilterEvaluationException, UnmappableException {
ResultSet rs = null;
PreparedStatement preparedStatement = null;
try {
AbstractWhereBuilder builder = getWhereBuilder( query, conn );
LOG.debug( "new Counting" );
StringBuilder getDatasetIDs = new StringBuilder();
getDatasetIDs.append( "SELECT " );
getDatasetIDs.append( "COUNT( DISTINCT(" );
getDatasetIDs.append( builder.getAliasManager().getRootTableAlias() );
getDatasetIDs.append( "." );
getDatasetIDs.append( idColumn );
getDatasetIDs.append( "))" );
getPSBody( builder, getDatasetIDs );
String sql = getDatasetIDs.toString();
LOG.trace( sql );
preparedStatement = createPreparedStatement( conn, sql );
int i = 1;
if ( builder.getWhere() != null ) {
for ( SQLArgument o : builder.getWhere().getArguments() ) {
o.setArgument( preparedStatement, i++ );
}
}
LOG.debug( preparedStatement.toString() );
rs = preparedStatement.executeQuery();
rs.next();
LOG.debug( "rs for rowCount: " + rs.getInt( 1 ) );
return rs.getInt( 1 );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", preparedStatement.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
JDBCUtils.close( rs, preparedStatement, conn, LOG );
}
}
@Override
public ISOMetadataResultSet executeGetRecordById( List<String> idList, Connection conn )
throws MetadataStoreException {
ResultSet rs = null;
PreparedStatement stmt = null;
try {
int size = idList.size();
StringBuilder select = new StringBuilder();
select.append( "SELECT " ).append( recordColumn );
select.append( " FROM " ).append( mainTable );
select.append( " WHERE " );
for ( int iter = 0; iter < size; iter++ ) {
select.append( fileIdColumn ).append( " = ? " );
if ( iter < size - 1 ) {
select.append( " OR " );
}
}
String sql = select.toString();
LOG.trace( sql );
stmt = createPreparedStatement( conn, sql );
stmt.setFetchSize( DEFAULT_FETCH_SIZE );
LOG.debug( "select RecordById statement: " + stmt );
int i = 1;
for ( String identifier : idList ) {
stmt.setString( i, identifier );
LOG.debug( "identifier: " + identifier );
LOG.debug( "" + stmt );
i++;
}
rs = stmt.executeQuery();
} catch ( Throwable t ) {
JDBCUtils.close( rs, stmt, conn, LOG );
String msg = Messages.getMessage( "ERROR_REQUEST_TYPE", ResultType.results.name(), t.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
// Don't close the ResultSet or PreparedStatement if no error occurs, the ResultSet is needed in the
// ISOMetadataResultSet and both will be closed by
// org.deegree.metadata.persistence.XMLMetadataResultSet#close().
}
return new ISOMetadataResultSet( rs, conn, stmt );
}
protected AbstractWhereBuilder getWhereBuilder( MetadataQuery query, Connection conn )
throws FilterEvaluationException, UnmappableException {
return dialect.getWhereBuilder( new ISOPropertyNameMapper( dialect, queryables ),
(OperatorFilter) query.getFilter(), query.getSorting(), false );
}
protected PreparedStatement createPreparedStatement( Connection conn, String sql )
throws SQLException {
PreparedStatement preparedStatement = conn.prepareStatement( sql );
preparedStatement.setQueryTimeout( QUERY_TIMEOUT_MS );
return preparedStatement;
}
}
|
package org.hisp.dhis.resourcetable.table;
import java.util.List;
import java.util.Optional;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.resourcetable.ResourceTable;
import com.google.common.collect.Lists;
/**
* @author Lars Helge Overland
*/
public class DataApprovalMinLevelResourceTable
extends ResourceTable<OrganisationUnitLevel>
{
public DataApprovalMinLevelResourceTable( List<OrganisationUnitLevel> objects, String columnQuote )
{
super( objects, columnQuote );
}
@Override
public String getTableName()
{
return "_dataapprovalminlevel";
}
@Override
public String getCreateTempTableStatement()
{
String sql = "create table " + getTempTableName() + "(" +
"datasetid integer not null, " +
"periodid integer not null, " +
"organisationunitid integer not null, " +
"attributeoptioncomboid integer not null, " +
"minlevel integer not null, " +
"primary key (datasetid,periodid,attributeoptioncomboid,organisationunitid))";
return sql;
}
@Override
public Optional<String> getPopulateTempTableStatement()
{
String sql =
"insert into " + getTempTableName() +
" (datasetid,periodid,organisationunitid,attributeoptioncomboid,minlevel) " +
"select da.datasetid, da.periodid, da.organisationunitid, da.attributeoptioncomboid, dal.level as minlevel " +
"from dataapproval da " +
"inner join dataapprovallevel dal on da.dataapprovallevelid=dal.dataapprovallevelid " +
"inner join _orgunitstructure ous on da.organisationunitid=ous.organisationunitid " +
"where not exists ( " +
"select 1 from dataapproval da2 " +
"inner join dataapprovallevel dal2 on da2.dataapprovallevelid=dal2.dataapprovallevelid " +
"where da.datasetid=da2.datasetid " +
"and da.periodid=da2.periodid " +
"and da.attributeoptioncomboid=da2.attributeoptioncomboid " +
"and dal.level > dal2.level " +
"and ( ";
for ( OrganisationUnitLevel level : objects )
{
sql += "ous.idlevel" + level.getLevel() + " = da2.organisationunitid or ";
}
sql = TextUtils.removeLastOr( sql ) + ") )";
return Optional.of( sql );
}
@Override
public Optional<List<Object[]>> getPopulateTempTableContent()
{
return Optional.empty();
}
@Override
public List<String> getCreateIndexStatements()
{
return Lists.newArrayList();
}
}
|
package edu.isi.karma.controller.command.alignment;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.repository.sail.SailRepositoryConnection;
import org.openrdf.rio.RDFFormat;
import org.openrdf.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.isi.karma.controller.command.alignment.GenerateR2RMLModelCommand.PreferencesKeys;
import edu.isi.karma.controller.history.IHistorySaver;
import edu.isi.karma.kr2rml.ErrorReport;
import edu.isi.karma.kr2rml.KR2RMLMappingWriter;
import edu.isi.karma.kr2rml.mapping.KR2RMLMapping;
import edu.isi.karma.kr2rml.mapping.KR2RMLMappingGenerator;
import edu.isi.karma.modeling.Namespaces;
import edu.isi.karma.modeling.Prefixes;
import edu.isi.karma.modeling.alignment.Alignment;
import edu.isi.karma.modeling.alignment.AlignmentManager;
import edu.isi.karma.modeling.alignment.IAlignmentSaver;
import edu.isi.karma.modeling.ontology.OntologyManager;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.webserver.ServletContextParameterMap;
import edu.isi.karma.webserver.ServletContextParameterMap.ContextParameter;
public class R2RMLAlignmentFileSaver implements IAlignmentSaver, IHistorySaver {
private static Logger logger = LoggerFactory
.getLogger(R2RMLAlignmentFileSaver.class);
private KR2RMLMappingGenerator alignmentMappingGenerator = null;
private String namespace;
private String prefix;
private Workspace workspace;
public R2RMLAlignmentFileSaver(Workspace workspace) {
this.workspace = workspace;
JSONObject prefObject = workspace.getCommandPreferences().getCommandPreferencesJSONObject(
"PublishRDFCommand"+"Preferences");
if (prefObject != null) {
namespace = prefObject.getString(PreferencesKeys.rdfNamespace.name());
prefix = prefObject.getString(PreferencesKeys.rdfPrefix.name());
namespace = ((namespace == null) || (namespace.equals(""))) ?
Namespaces.KARMA_DEV : namespace;
prefix = ((prefix == null) || (prefix.equals(""))) ?
Prefixes.KARMA_DEV : prefix;
} else {
namespace = Namespaces.KARMA_DEV;
prefix = Prefixes.KARMA_DEV;
}
}
@Override
public void saveAlignment(Alignment alignment) throws Exception {
saveAlignment(alignment, null, null);
}
public void saveAlignment(Alignment alignment, JSONArray history) throws Exception {
saveAlignment(alignment, history, null);
}
public void saveAlignment(Alignment alignment, String modelFilename) throws Exception {
saveAlignment(alignment, null, modelFilename);
}
public void saveAlignment(Alignment alignment, JSONArray history, String modelFilename) throws Exception {
long start = System.currentTimeMillis();
String workspaceId = AlignmentManager.Instance().getWorkspaceId(alignment);
String worksheetId = AlignmentManager.Instance().getWorksheetId(alignment);
Worksheet worksheet = workspace.getWorksheet(worksheetId);
if(modelFilename == null && worksheet != null) {
modelFilename = getHistoryFilepath(worksheetId);
}
long end1 = System.currentTimeMillis();
logger.info("Time to get alignment info for saving: " + (end1-start) + "msec");
// Generate the KR2RML data structures for the RDF generation
final ErrorReport errorReport = new ErrorReport();
if (worksheet != null)
alignmentMappingGenerator = new KR2RMLMappingGenerator(workspace, worksheet, alignment,
worksheet.getSemanticTypes(), prefix, namespace, true, history, errorReport);
long end2 = System.currentTimeMillis();
logger.info("Time to generate mappings:" + (end2-end1) + "msec");
// Write the model
if (modelFilename != null && !modelFilename.trim().isEmpty())
writeModel(workspace, workspace.getOntologyManager(), alignmentMappingGenerator, worksheet, modelFilename);
logger.info("Alignment for " + workspaceId + ":" + worksheetId + " saved to file: " + modelFilename);
long end3 = System.currentTimeMillis();
logger.info("Time to write to file:" + (end3-end2) + "msec");
}
public KR2RMLMapping getMappings() {
return alignmentMappingGenerator.getKR2RMLMapping();
}
private void writeModel(Workspace workspace, OntologyManager ontMgr,
KR2RMLMappingGenerator mappingGen, Worksheet worksheet, String modelFileLocalPath)
throws RepositoryException, FileNotFoundException,
UnsupportedEncodingException, JSONException {
File f = new File(modelFileLocalPath);
File parentDir = f.getParentFile();
parentDir.mkdirs();
PrintWriter writer = new PrintWriter(f, "UTF-8");
KR2RMLMappingWriter mappingWriter = new KR2RMLMappingWriter();
mappingWriter.addR2RMLMapping(mappingGen.getKR2RMLMapping(), worksheet, workspace);
mappingWriter.writeR2RMLMapping(writer);
mappingWriter.close();
writer.flush();
writer.close();
}
@Override
public String getHistoryFilepath(String worksheetId) {
Worksheet worksheet = workspace.getWorksheet(worksheetId);
String modelFilename = workspace.getCommandPreferencesId() + worksheetId + "-" +
worksheet.getTitle() + "-auto-model.ttl";
String modelFileLocalPath = ServletContextParameterMap.getParameterValue(
ContextParameter.R2RML_USER_DIR) + modelFilename;
return modelFileLocalPath;
}
@Override
public void saveHistory(String workspaceId, String worksheetId,
JSONArray history) throws Exception {
Alignment alignment = AlignmentManager.Instance().getAlignment(workspaceId, worksheetId);
this.saveAlignment(alignment, history);
}
@Override
public JSONArray loadHistory(String filename) throws Exception {
File file = new File(filename);
// String encoding = EncodingDetector.detect(file);
// String contents = EncodingDetector.getString(file, encoding);
SailRepository myRepository = new SailRepository(new MemoryStore());
myRepository.initialize();
SailRepositoryConnection con = myRepository.getConnection();
con.add(file, "", RDFFormat.TURTLE);
RepositoryResult<Statement> result = con.getStatements(null, new URIImpl("http://isi.edu/integration/karma/dev#hasWorksheetHistory"), null, false);
if(result.hasNext()) {
Statement stmt = result.next();
String history = stmt.getObject().stringValue();
return new JSONArray(history);
}
return new JSONArray();
}
}
|
package org.apereo.cas.authentication;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapSearchProperties;
import org.apereo.cas.util.LdapUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.ldaptive.AttributeModification;
import org.ldaptive.AttributeModificationType;
import org.ldaptive.ConnectionFactory;
import org.ldaptive.LdapAttribute;
import org.ldaptive.ModifyOperation;
import org.ldaptive.ModifyRequest;
import org.ldaptive.ResultCode;
import org.ldaptive.ad.UnicodePwdAttribute;
import java.util.Collections;
import java.util.Optional;
/**
* This is {@link LdapPasswordSynchronizationAuthenticationPostProcessor}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
@Slf4j
public class LdapPasswordSynchronizationAuthenticationPostProcessor implements AuthenticationPostProcessor {
private final ConnectionFactory searchFactory;
private final AbstractLdapSearchProperties ldapProperties;
public LdapPasswordSynchronizationAuthenticationPostProcessor(final AbstractLdapSearchProperties properties) {
this.ldapProperties = properties;
this.searchFactory = LdapUtils.newLdaptivePooledConnectionFactory(properties);
}
@Override
public void process(final AuthenticationBuilder builder, final AuthenticationTransaction transaction) throws AuthenticationException {
val primaryCredential = transaction.getPrimaryCredential();
if (primaryCredential.isEmpty()) {
LOGGER.warn("Current authentication transaction does not have a primary credential");
return;
}
try {
val credential = UsernamePasswordCredential.class.cast(primaryCredential.get());
val filter = LdapUtils.newLdaptiveSearchFilter(ldapProperties.getSearchFilter(),
LdapUtils.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, Collections.singletonList(credential.getUsername()));
LOGGER.trace("Constructed LDAP filter [{}] to locate user and update password", filter);
val response = LdapUtils.executeSearchOperation(searchFactory, ldapProperties.getBaseDn(), filter);
LOGGER.debug("LDAP response is [{}]", response);
if (LdapUtils.containsResultEntry(response)) {
val dn = response.getResult().getEntry().getDn();
LOGGER.trace("Updating account password for [{}]", dn);
try (val modifyConnection = LdapUtils.createConnection(searchFactory)) {
val operation = new ModifyOperation(modifyConnection);
val mod = new AttributeModification(AttributeModificationType.REPLACE, getLdapPasswordAttribute(credential));
val updateResponse = operation.execute(new ModifyRequest(dn, mod));
LOGGER.trace("Result code [{}], message: [{}]", response.getResult(), response.getMessage());
val result = updateResponse.getResultCode() == ResultCode.SUCCESS;
if (result) {
LOGGER.info("Updated the LDAP entry's password for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
} else {
LOGGER.warn("Could not update the LDAP entry's password for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
}
}
} else {
LOGGER.error("Could not locate an LDAP entry for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
@Override
public boolean supports(final Credential credential) {
return credential instanceof UsernamePasswordCredential;
}
/**
* Gets ldap password attribute.
*
* @param credential the credential
* @return the ldap password attribute
*/
protected LdapAttribute getLdapPasswordAttribute(final UsernamePasswordCredential credential) {
return new UnicodePwdAttribute(credential.getPassword());
}
}
|
package uk.ac.york.mondo.integration.hawk.servlet.artemis;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnectorFactory;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TTransport;
import org.hawk.core.IModelIndexer;
import org.hawk.core.VcsChangeType;
import org.hawk.core.VcsCommit;
import org.hawk.core.VcsCommitItem;
import org.hawk.core.VcsRepository;
import org.hawk.core.VcsRepositoryDelta;
import org.hawk.core.graph.IGraphChangeListener;
import org.hawk.core.graph.IGraphNode;
import org.hawk.core.model.IHawkClass;
import org.hawk.core.model.IHawkObject;
import org.hawk.core.model.IHawkPackage;
import org.hawk.core.runtime.CompositeGraphChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.york.mondo.integration.api.CommitItem;
import uk.ac.york.mondo.integration.api.CommitItemChangeType;
import uk.ac.york.mondo.integration.api.HawkAttributeRemovalEvent;
import uk.ac.york.mondo.integration.api.HawkAttributeUpdateEvent;
import uk.ac.york.mondo.integration.api.HawkChangeEvent;
import uk.ac.york.mondo.integration.api.HawkFileAdditionEvent;
import uk.ac.york.mondo.integration.api.HawkFileRemovalEvent;
import uk.ac.york.mondo.integration.api.HawkModelElementAdditionEvent;
import uk.ac.york.mondo.integration.api.HawkModelElementRemovalEvent;
import uk.ac.york.mondo.integration.api.HawkReferenceAdditionEvent;
import uk.ac.york.mondo.integration.api.HawkReferenceRemovalEvent;
import uk.ac.york.mondo.integration.api.HawkSynchronizationEndEvent;
import uk.ac.york.mondo.integration.api.HawkSynchronizationStartEvent;
import uk.ac.york.mondo.integration.api.SubscriptionDurability;
import uk.ac.york.mondo.integration.api.utils.APIUtils.ThriftProtocol;
import uk.ac.york.mondo.integration.api.utils.ActiveMQBufferTransport;
import uk.ac.york.mondo.integration.hawk.servlet.utils.HawkModelElementEncoder;
/**
* Hawk change listener that sends all changes to the specified address within
* an Artemis in-VM server through its core protocol. Transaction management is
* based on the {@link TransactionalSendTest} test suite in Artemis.
*
* This implementation redefines hashCode and equals based on the computed
* address, so "duplicate" listeners that would result in duplicate events being
* sent to the destination address are implicitly avoided by the
* {@link CompositeGraphChangeListener} in most indexers.
*/
public class ArtemisProducerGraphChangeListener implements IGraphChangeListener {
private static final Logger LOGGER = LoggerFactory
.getLogger(ArtemisProducerGraphChangeListener.class);
private final ServerLocator locator;
private final ClientSessionFactory sessionFactory;
private final boolean messagesAreDurable;
private final String queueAddress;
private final TProtocolFactory protocolFactory;
private ClientSession session;
private ClientProducer producer;
private final Pattern repositoryURIPattern, filePathPattern;
// True if the current session was opened from synchronizeStart
private boolean isSessionOpenedFromSync = false;
public ArtemisProducerGraphChangeListener(String hawkInstance,
String repositoryUri, List<String> filePaths,
SubscriptionDurability durability, ThriftProtocol protocol)
throws Exception {
// Convert the repository URI and file paths into regexps, for faster
// matching
this.repositoryURIPattern = Pattern.compile(repositoryUri.replace("*",
".*"));
StringBuffer sbuf = new StringBuffer();
boolean first = true;
for (String filePath : filePaths) {
if (first) {
first = false;
} else {
sbuf.append("|");
}
sbuf.append(filePath.replace("*", ".*"));
}
this.filePathPattern = Pattern.compile(sbuf.toString());
// Thrift protocol factory (for encoding the events)
this.protocolFactory = protocol.getProtocolFactory();
// Connect to Artemis (use compression for messages above 10KB)
this.locator = ActiveMQClient
.createServerLocatorWithoutHA(new TransportConfiguration(
InVMConnectorFactory.class.getName()));
locator.setCompressLargeMessage(true);
locator.setMinLargeMessageSize(10_240);
this.sessionFactory = locator.createSessionFactory();
this.messagesAreDurable = durability == SubscriptionDurability.DURABLE;
this.queueAddress = String.format("hawk.graphchanges.%s.%s.%s.%s.%s",
hawkInstance, protocol.toString().toLowerCase(), repositoryUri
.hashCode(), filePaths.hashCode(), durability
.toString().toLowerCase());
}
public String getQueueAddress() {
return queueAddress;
}
@Override
public String getName() {
return "Artemis graph change listener";
}
@Override
public void synchroniseStart() {
openSession();
isSessionOpenedFromSync = true;
final HawkSynchronizationStartEvent ev = new HawkSynchronizationStartEvent(System.nanoTime());
final HawkChangeEvent change = new HawkChangeEvent();
change.setSyncStart(ev);
sendEvent(change);
try {
session.commit();
} catch (ActiveMQException e) {
LOGGER.error("Could not commit the synchronisation start event", e);
}
}
@Override
public void synchroniseEnd() {
try {
final HawkSynchronizationEndEvent ev = new HawkSynchronizationEndEvent(System.nanoTime());
final HawkChangeEvent change = new HawkChangeEvent();
change.setSyncEnd(ev);
sendEvent(change);
session.commit();
} catch (ActiveMQException e) {
LOGGER.error("Could not commit the transaction", e);
} finally {
closeSession();
}
}
@Override
public void changeStart() {
openSession();
}
@Override
public void changeSuccess() {
try {
session.commit();
} catch (ActiveMQException e) {
LOGGER.error("Could not commit the transaction", e);
try {
session.rollback();
} catch (ActiveMQException e1) {
LOGGER.error("Could not rollback the transaction", e1);
}
} finally {
if (!isSessionOpenedFromSync) {
closeSession();
}
}
}
@Override
public void changeFailure() {
try {
session.rollback();
LOGGER.debug("Session rolled back");
} catch (ActiveMQException e) {
LOGGER.error("Could not rollback the transaction", e);
} finally {
if (!isSessionOpenedFromSync) {
closeSession();
}
}
}
@Override
public void metamodelAddition(IHawkPackage pkg, IGraphNode pkgNode) {
// nothing to do!
}
@Override
public void classAddition(IHawkClass cls, IGraphNode clsNode) {
// nothing to do!
}
@Override
public void fileAddition(VcsCommitItem s, IGraphNode fileNode) {
if (!isAcceptedByFilter(s))
return;
final HawkFileAdditionEvent ev = new HawkFileAdditionEvent();
ev.setVcsItem(mapToThrift(s));
final HawkChangeEvent change = new HawkChangeEvent();
change.setFileAddition(ev);
sendEvent(change);
}
@Override
public void fileRemoval(VcsCommitItem s, IGraphNode fileNode) {
if (!isAcceptedByFilter(s))
return;
final HawkFileRemovalEvent ev = new HawkFileRemovalEvent();
ev.setVcsItem(mapToThrift(s));
final HawkChangeEvent change = new HawkChangeEvent();
change.setFileRemoval(ev);
sendEvent(change);
}
@Override
public void modelElementAddition(VcsCommitItem s, IHawkObject element,
IGraphNode elementNode, boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
try {
final HawkModelElementAdditionEvent ev = new HawkModelElementAdditionEvent();
ev.setVcsItem(mapToThrift(s));
ev.setMetamodelURI(element.getType().getPackageNSURI());
ev.setTypeName(element.getType().getName());
ev.setId(elementNode.getId().toString());
final HawkChangeEvent change = new HawkChangeEvent();
change.setModelElementAddition(ev);
sendEvent(change);
} catch (Exception e) {
LOGGER.error("Could not encode a model element", e);
}
}
@Override
public void modelElementRemoval(VcsCommitItem s, IGraphNode elementNode,
boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
final HawkModelElementRemovalEvent ev = new HawkModelElementRemovalEvent();
ev.setVcsItem(mapToThrift(s));
ev.setId(elementNode.getId().toString());
final HawkChangeEvent change = new HawkChangeEvent();
change.setModelElementRemoval(ev);
sendEvent(change);
}
@Override
public void modelElementAttributeUpdate(VcsCommitItem s,
IHawkObject eObject, String attrName, Object oldValue,
Object newValue, IGraphNode elementNode, boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
final HawkAttributeUpdateEvent ev = new HawkAttributeUpdateEvent();
ev.setAttribute(attrName);
ev.setId(elementNode.getId().toString());
ev.setValue(HawkModelElementEncoder.encodeAttributeSlot(attrName,
newValue).value);
ev.setVcsItem(mapToThrift(s));
final HawkChangeEvent change = new HawkChangeEvent();
change.setModelElementAttributeUpdate(ev);
sendEvent(change);
}
@Override
public void modelElementAttributeRemoval(VcsCommitItem s,
IHawkObject eObject, String attrName, IGraphNode elementNode,
boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
final HawkAttributeRemovalEvent ev = new HawkAttributeRemovalEvent();
ev.setAttribute(attrName);
ev.setId(elementNode.getId().toString());
ev.setVcsItem(mapToThrift(s));
final HawkChangeEvent change = new HawkChangeEvent();
change.setModelElementAttributeRemoval(ev);
sendEvent(change);
}
@Override
public void referenceAddition(VcsCommitItem s, IGraphNode source,
IGraphNode target, String refName, boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
final HawkReferenceAdditionEvent ev = new HawkReferenceAdditionEvent();
ev.setSourceId(source.getId().toString());
ev.setTargetId(target.getId().toString());
ev.setVcsItem(mapToThrift(s));
ev.setRefName(refName);
final HawkChangeEvent change = new HawkChangeEvent();
change.setReferenceAddition(ev);
sendEvent(change);
}
@Override
public void referenceRemoval(VcsCommitItem s, IGraphNode source,
IGraphNode target, String refName, boolean isTransient) {
if (isTransient || !isAcceptedByFilter(s))
return;
final HawkReferenceRemovalEvent ev = new HawkReferenceRemovalEvent();
ev.setSourceId(source.getId().toString());
ev.setTargetId(target.getId().toString());
ev.setVcsItem(mapToThrift(s));
ev.setRefName(refName);
final HawkChangeEvent change = new HawkChangeEvent();
change.setReferenceRemoval(ev);
sendEvent(change);
}
private boolean isAcceptedByFilter(VcsCommitItem s) {
final VcsCommit commit = s.getCommit();
final VcsRepositoryDelta delta = commit.getDelta();
final VcsRepository repository = delta.getRepository();
final String repositoryURL = repository.getUrl();
return repositoryURIPattern.matcher(repositoryURL).matches()
&& filePathPattern.matcher(s.getPath()).matches();
}
private CommitItem mapToThrift(VcsCommitItem s) {
final VcsCommit commit = s.getCommit();
final String repoURL = commit.getDelta().getRepository().getUrl();
final String revision = commit.getRevision();
final String path = s.getPath();
final CommitItemChangeType changeType = mapToThrift(s.getChangeType());
return new CommitItem(repoURL, revision, path, changeType);
}
private CommitItemChangeType mapToThrift(VcsChangeType changeType) {
switch (changeType) {
case ADDED:
return CommitItemChangeType.ADDED;
case DELETED:
return CommitItemChangeType.DELETED;
case REPLACED:
return CommitItemChangeType.REPLACED;
case UPDATED:
return CommitItemChangeType.UPDATED;
default:
return CommitItemChangeType.UNKNOWN;
}
}
private void sendEvent(HawkChangeEvent change) {
try {
final ClientMessage msg = session.createMessage(Message.BYTES_TYPE,
messagesAreDurable);
final TTransport trans = new ActiveMQBufferTransport(
msg.getBodyBuffer());
final TProtocol proto = protocolFactory.getProtocol(trans);
change.write(proto);
producer.send(msg);
} catch (TException ex) {
LOGGER.error("Serialization error", ex);
} catch (ActiveMQException ex) {
LOGGER.error("Error while sending event", ex);
}
}
private void openSession() {
if (session == null) {
try {
this.session = sessionFactory.createSession(false, false, false);
this.producer = session.createProducer(queueAddress);
} catch (ActiveMQException e) {
LOGGER.error("Could not start a new Artemis session", e);
}
}
}
private void closeSession() {
try {
if (producer != null) {
producer.close();
}
if (session != null) {
session.close();
}
} catch (ActiveMQException e) {
LOGGER.error("Could not close the session", e);
} finally {
session = null;
isSessionOpenedFromSync = false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((queueAddress == null) ? 0 : queueAddress.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;
ArtemisProducerGraphChangeListener other = (ArtemisProducerGraphChangeListener) obj;
if (queueAddress == null) {
if (other.queueAddress != null)
return false;
} else if (!queueAddress.equals(other.queueAddress))
return false;
return true;
}
@Override
public void setModelIndexer(IModelIndexer m) {
// not used
}
}
|
package org.csstudio.opibuilder.validation.core;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.preferences.PreferencesHelper;
import org.csstudio.opibuilder.validation.Activator;
import org.csstudio.opibuilder.validation.core.ui.ContentProvider;
import org.csstudio.opibuilder.validation.core.ui.TreeViewerListener;
import org.csstudio.opibuilder.validation.ui.ResultsDialog;
import org.eclipse.core.internal.resources.Workspace;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
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.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.internal.SWTEventListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TypedListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.views.markers.ExtendedMarkersView;
import org.eclipse.ui.internal.views.markers.ProblemsView;
import org.eclipse.wst.validation.AbstractValidator;
import org.eclipse.wst.validation.ValidationResult;
import org.eclipse.wst.validation.ValidationState;
import org.eclipse.wst.validation.ValidatorMessage;
/**
*
* <code>Validator</code> implements the wst validation api for validating OPI files. OPIs are validated by comparing
* their values to the ones defined in the OPI schema.
*
* @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a>
*
*/
@SuppressWarnings("restriction")
public class Validator extends AbstractValidator {
private static class NonNullHashMap<K, T> extends HashMap<K, T> {
private static final long serialVersionUID = 7385574868370529896L;
@Override
public T put(K key, T value) {
if (value == null) {
return null;
}
return super.put(key, value);
}
}
private static final Logger LOGGER = Logger.getLogger(Validator.class.getName());
/** Marker name for OPI validation failure */
public static final String MARKER_PROBLEM = Activator.ID + ".opiValidationProblem";
/** Marker name for OPI loading error */
public static final String MARKER_ERROR = Activator.ID + ".opiLoadingError";
/** The ID of the editor to open when the marker is double clicked */
private static final String DEFAULT_TEXT_EDITOR = "org.eclipse.ui.DefaultTextEditor";
/** The name of the marker attribute that contains the validation failure */
public static final String ATTR_VALIDATION_FAILURE = "validationFailure";
private SchemaVerifier verifier;
// if a rule matches this pattern it defines a property, if it doesn't match, the rule is a regex
private static final Pattern TRUE_PROPERTY_PATTERN = Pattern.compile("[0-9a-z_\\.]*");
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.validation.AbstractValidator#validate(org.eclipse.core.resources.IResource, int,
* org.eclipse.wst.validation.ValidationState, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
if (resource.getType() != IResource.FILE) {
return null;
}
if (monitor.isCanceled()) {
return null;
}
try {
if (!Utilities.shouldContinueIfFileOpen("validation", resource)) {
monitor.setCanceled(true);
return null;
}
} catch (PartInitException e) {
LOGGER.log(Level.SEVERE, "Could not obtain editor inputs.", e);
monitor.setCanceled(true);
return null;
}
boolean useDefaultEditor = Activator.getInstance().isShowMarkersInDefaultEditor();
ValidationResult result = new ValidationResult();
try {
ValidationFailure[] failures = verifier.validate(resource.getFullPath());
ValidatorMessage message;
for (ValidationFailure vf : failures) {
message = createMessage(vf, resource, useDefaultEditor);
result.add(message);
if (vf.hasSubFailures()) {
for (SubValidationFailure f : vf.getSubFailures()) {
message = createMessage(f, resource, useDefaultEditor);
result.add(message);
}
}
}
} catch (IOException e) {
ValidatorMessage message = ValidatorMessage.create(e.getMessage(), resource);
message.setType(MARKER_ERROR);
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
message.setAttribute(IMarker.LOCATION, resource.getFullPath().toFile().getAbsolutePath());
result.add(message);
}
return result;
}
private ValidatorMessage createMessage(ValidationFailure vf, IResource resource, boolean useDefaultEditor) {
if (vf instanceof SubValidationFailure) {
IResource res = ((SubValidationFailure) vf).getResource();
if (res != null) {
resource = res;
}
}
ValidatorMessage message = ValidatorMessage.create(vf.getMessage(), resource);
message.setType(MARKER_PROBLEM);
if (vf.getRule() == ValidationRule.RO) {
if (vf.isCritical()) {
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
} else {
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
}
} else if (vf.getRule() == ValidationRule.WRITE) {
if (vf.isCritical()) {
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
} else {
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
}
} else if (vf.getRule() == ValidationRule.RW) {
// Can happen in the font and colour case
message.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
}
message.setAttribute(IMarker.LOCATION, vf.getLocation());
message.setAttribute(IMarker.LINE_NUMBER, vf.getLineNumber());
message.setAttribute(ATTR_VALIDATION_FAILURE, vf);
message.setAttribute(AbstractWidgetModel.PROP_WIDGET_UID, vf.getWUID());
if (!useDefaultEditor) {
message.setAttribute(IDE.EDITOR_ID_ATTR, DEFAULT_TEXT_EDITOR);
}
return message;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.validation.AbstractValidator#validationStarting(org.eclipse.core.resources.IProject,
* org.eclipse.wst.validation.ValidationState, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor) {
if (project == null) {
if (Activator.getInstance().isClearMarkers()) {
try {
// cleanup all opi validation markers
ResourcesPlugin.getWorkspace().getRoot().deleteMarkers(MARKER_PROBLEM, true,
IProject.DEPTH_INFINITE);
ResourcesPlugin.getWorkspace().getRoot().deleteMarkers(MARKER_ERROR, true, IProject.DEPTH_INFINITE);
//This is wrong, but it is the only way to convince eclipse to forget about the existing markers
//If validated opis have lots of issues, there will be a lot of markers. Because a marker contains a
//reference to the failure and a failure might contain a reference to a widget model, a lot of
//memory might be needed to keep track of everything. The markers are kept in the save manager
//~forever(?!) and this appears to be the only way to clear them permanently and free the memory.
((Workspace)ResourcesPlugin.getWorkspace()).getSaveManager().startup(monitor);
} catch (CoreException e) {
LOGGER.log(Level.WARNING, "Could not delete opi validation markers.", e);
}
}
// bring the progress view to the top
showView("org.eclipse.ui.views.ProgressView", false);
// reload the rules, just in case they have been changed
IPath rulesFile = Activator.getInstance().getRulesFile();
verifier = createVerifier(PreferencesHelper.getSchemaOPIPath(), rulesFile, monitor);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.validation.AbstractValidator#validationFinishing(org.eclipse.core.resources.IProject,
* org.eclipse.wst.validation.ValidationState, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor) {
if (project == null) {
// at the end bring the problems view to the top and if requested show the summary dialog
showView("org.eclipse.ui.views.ProblemView", true);
if (Activator.getInstance().isShowSummaryDialog()) {
final SchemaVerifier sv = verifier;
Display.getDefault().asyncExec(() -> {
IWorkbenchPage page = getPage();
new ResultsDialog(page.getWorkbenchWindow().getShell(), sv.getNumberOfAnalyzedFiles(),
sv.getNumberOfFilesFailures(), sv.getNumberOfAnalyzedWidgets(), sv.getNumberOfWidgetsFailures(),
sv.getNumberOfROProperties(), sv.getNumberOfCriticalROFailures(),
sv.getNumberOfMajorROFailures(), sv.getNumberOfWRITEProperties(), sv.getNumberOfWRITEFailures(),
sv.getNumberOfRWProperties(), sv.getNumberOfRWFailures(), sv.getNumberOfDeprecatedFailures(),
sv.getNumberOfWidgetsWithRules(), sv.getNumberOfAllRules(), sv.getNumberOfWidgetsWithScripts(),
sv.getNumberOfWidgetsWithPythonEmbedded(), sv.getNumberOfWidgetsWithJavascriptEmbedded(),
sv.getNumberOfWidgetsWithPythonStandalone(), sv.getNumberOfWidgetsWithJavascriptStandalone())
.open();
});
}
//remove reference to the verifier, so that GC can take it
verifier = null;
}
}
private static void showView(final String view, final boolean update) {
Display.getDefault().asyncExec(() -> {
try {
IWorkbenchPage page = getPage();
if (page != null) {
page.showView(view);
if (update) {
updateProblemsView(page);
}
}
} catch (PartInitException e) {
LOGGER.log(Level.WARNING, "Could not open the view '" + view + "'.", e);
}
});
}
private static void updateProblemsView(IWorkbenchPage page) {
try {
ProblemsView v = (ProblemsView) page.showView("org.eclipse.ui.views.ProblemView");
Field f = ExtendedMarkersView.class.getDeclaredField("viewer");
f.setAccessible(true);
TreeViewer viewer = (TreeViewer) f.get(v);
ITreeContentProvider provider = (ITreeContentProvider) viewer.getContentProvider();
if (!(provider instanceof ContentProvider)) {
viewer.setContentProvider(new ContentProvider(provider));
Listener[] exp = viewer.getTree().getListeners(SWT.Expand);
Listener[] col = viewer.getTree().getListeners(SWT.Collapse);
for (int i = 0; i < exp.length; i++) {
if (exp[i] instanceof TypedListener) {
SWTEventListener l = ((TypedListener) exp[i]).getEventListener();
if (l.getClass().getName().contains("ExtendedMarkersView")) {
viewer.getTree().removeListener(SWT.Expand, exp[i]);
viewer.getTree().addListener(SWT.Expand,
new TypedListener(new TreeViewerListener((TreeListener) l)));
}
}
}
for (int i = 0; i < col.length; i++) {
if (col[i] instanceof TypedListener) {
SWTEventListener l = ((TypedListener) col[i]).getEventListener();
if (l.getClass().getName().contains("ExtendedMarkersView")) {
viewer.getTree().removeListener(SWT.Collapse, col[i]);
viewer.getTree().addListener(SWT.Collapse,
new TypedListener(new TreeViewerListener((TreeListener) l)));
}
}
}
}
} catch (IllegalAccessException | NoSuchFieldException | RuntimeException | PartInitException e) {
// ignore
// cannot update view, we will use the original one
}
}
private static IWorkbenchPage getPage() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null && PlatformUI.getWorkbench().getWorkbenchWindowCount() > 0) {
window = PlatformUI.getWorkbench().getWorkbenchWindows()[0];
}
if (window == null) {
return null;
}
IWorkbenchPage page = window.getActivePage();
if (page == null && window.getPages().length > 0) {
page = window.getPages()[0];
}
return page;
}
/**
* Creates a verifier based on the schema and rules.
*
* @param schema the path to the OPI schema against which the files will be verified
* @param rulesFile the file containing the validation rules
* @param monitor a monitor which is cancelled in case of failure (can be null)
* @return schema verifier
*/
public static SchemaVerifier createVerifier(IPath schema, IPath rulesFile, IProgressMonitor monitor) {
Map<String, ValidationRule> rules = new HashMap<>();
Map<Pattern, ValidationRule> rulePatterns = new HashMap<>();
Map<String, String[]> acceptableValues = new NonNullHashMap<>();
Map<Pattern, String[]> acceptableValuesPatterns = new NonNullHashMap<>();
Map<String, String[]> removedValues = new NonNullHashMap<>();
Map<Pattern, String[]> removedValuesPatterns = new NonNullHashMap<>();
if (rulesFile != null) {
Properties p = new Properties();
try (FileInputStream stream = new FileInputStream(rulesFile.toFile())) {
p.load(stream);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Cannot read the rules definition file: " + rulesFile.toOSString(), e);
if (monitor != null) {
monitor.setCanceled(true);
}
}
String ruleStr;
for (Entry<Object, Object> e : p.entrySet()) {
String key = ((String) e.getKey()).toLowerCase(Locale.UK);
String value = (String) e.getValue();
int idx = value.indexOf('[');
int idxRem = value.indexOf('{');
String[] acceptables = null;
String[] removies = null;
if (idx > 0 || idxRem > 0) {
if (idx > 0 && idxRem > 0) {
ruleStr = value.substring(0, Math.min(idx, idxRem)).trim();
} else if (idx > 0) {
ruleStr = value.substring(0, idx).trim();
} else {
ruleStr = value.substring(0, idxRem).trim();
}
try {
if (idx > 0) {
acceptables = value.substring(idx + 1, value.indexOf(']')).split("\\;");
for (int i = 0; i < acceptables.length; i++) {
acceptables[i] = acceptables[i].trim();
}
}
if (idxRem > 0) {
removies = value.substring(idxRem + 1, value.indexOf('}')).split("\\;");
for (int i = 0; i < removies.length; i++) {
removies[i] = removies[i].trim();
}
}
} catch (RuntimeException ex) {
// in case that acceptables cannot be parsed, just ignore them
LOGGER.log(Level.WARNING, "The rule for property '" + key + "' is incorrectly defined."
+ " Check the alternative acceptable and removed values definition.");
}
} else {
ruleStr = value;
}
try {
ValidationRule rule = ValidationRule.valueOf(ruleStr.toUpperCase(Locale.UK));
if (TRUE_PROPERTY_PATTERN.matcher(key).matches()) {
rules.put(key, rule);
acceptableValues.put(key, acceptables);
removedValues.put(key, removies);
} else {
Pattern ptrn = Pattern.compile(key);
rulePatterns.put(ptrn, rule);
acceptableValuesPatterns.put(ptrn, acceptables);
removedValuesPatterns.put(ptrn, removies);
}
} catch (IllegalArgumentException ex) {
LOGGER.log(Level.WARNING, e.getKey() + " is not defined correctly.");
}
}
}
return new SchemaVerifier(schema, rules, rulePatterns, acceptableValues, acceptableValuesPatterns,
removedValues, removedValuesPatterns);
}
}
|
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.components.simplefileio;
import org.talend.components.common.dataset.DatasetProperties;
import org.talend.daikon.properties.PropertiesImpl;
import org.talend.daikon.properties.ReferenceProperties;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.property.Property;
import org.talend.daikon.properties.property.PropertyFactory;
public class SimpleFileIODatasetProperties extends PropertiesImpl implements DatasetProperties<SimpleFileIODatastoreProperties> {
public Property<SimpleFileIOFormat> format = PropertyFactory.newEnum("format", SimpleFileIOFormat.class).setRequired();
public Property<String> path = PropertyFactory.newString("path", "").setRequired();
public Property<RecordDelimiterType> recordDelimiter = PropertyFactory.newEnum("recordDelimiter", RecordDelimiterType.class)
.setValue(RecordDelimiterType.LF);
public Property<String> specificRecordDelimiter = PropertyFactory.newString("specificRecordDelimiter", "\\n");
public Property<FieldDelimiterType> fieldDelimiter = PropertyFactory.newEnum("fieldDelimiter", FieldDelimiterType.class)
.setValue(FieldDelimiterType.SEMICOLON);
public Property<String> specificFieldDelimiter = PropertyFactory.newString("specificFieldDelimiter", ";");
public final transient ReferenceProperties<SimpleFileIODatastoreProperties> datastoreRef = new ReferenceProperties<>(
"datastoreRef", SimpleFileIODatastoreDefinition.NAME);
public SimpleFileIODatasetProperties(String name) {
super(name);
}
@Override
public SimpleFileIODatastoreProperties getDatastoreProperties() {
return datastoreRef.getReference();
}
@Override
public void setDatastoreProperties(SimpleFileIODatastoreProperties datastoreProperties) {
datastoreRef.setReference(datastoreProperties);
}
@Override
public void setupProperties() {
super.setupProperties();
format.setValue(SimpleFileIOFormat.CSV);
}
@Override
public void setupLayout() {
super.setupLayout();
Form mainForm = new Form(this, Form.MAIN);
mainForm.addRow(path);
mainForm.addRow(format);
mainForm.addRow(recordDelimiter);
mainForm.addRow(specificRecordDelimiter);
mainForm.addRow(fieldDelimiter);
mainForm.addRow(specificFieldDelimiter);
}
@Override
public void refreshLayout(Form form) {
super.refreshLayout(form);
// Main properties
if (form.getName().equals(Form.MAIN)) {
form.getWidget(recordDelimiter).setVisible(format.getValue() == SimpleFileIOFormat.CSV);
form.getWidget(specificRecordDelimiter).setVisible(
format.getValue() == SimpleFileIOFormat.CSV && recordDelimiter.getValue().equals(RecordDelimiterType.OTHER));
form.getWidget(fieldDelimiter).setVisible(format.getValue() == SimpleFileIOFormat.CSV);
form.getWidget(specificFieldDelimiter).setVisible(
format.getValue() == SimpleFileIOFormat.CSV && fieldDelimiter.getValue().equals(FieldDelimiterType.OTHER));
}
}
public void afterFieldDelimiter() {
refreshLayout(getForm(Form.MAIN));
}
public void afterRecordDelimiter() {
refreshLayout(getForm(Form.MAIN));
}
public String getRecordDelimiter() {
if (RecordDelimiterType.OTHER.equals(recordDelimiter.getValue())) {
return specificRecordDelimiter.getValue();
} else {
return recordDelimiter.getValue().getDelimiter();
}
}
public String getFieldDelimiter() {
if (FieldDelimiterType.OTHER.equals(fieldDelimiter.getValue())) {
return specificFieldDelimiter.getValue();
} else {
return fieldDelimiter.getValue().getDelimiter();
}
}
public void afterFormat() {
refreshLayout(getForm(Form.MAIN));
}
public enum RecordDelimiterType {
LF("\n"),
CR("\r"),
CRLF("\r\n"),
OTHER("Other");
private final String value;
private RecordDelimiterType(final String value) {
this.value = value;
}
public String getDelimiter() {
return value;
}
}
public enum FieldDelimiterType {
SEMICOLON(";"),
COMMA(","),
TABULATION("\t"),
SPACE(" "),
OTHER("Other");
private final String value;
private FieldDelimiterType(final String value) {
this.value = value;
}
public String getDelimiter() {
return value;
}
}
}
|
package org.innovateuk.ifs.project.projectdetails.transactional;
import org.innovateuk.ifs.BaseServiceUnitTest;
import org.innovateuk.ifs.address.domain.Address;
import org.innovateuk.ifs.address.domain.AddressType;
import org.innovateuk.ifs.address.mapper.AddressMapper;
import org.innovateuk.ifs.address.repository.AddressRepository;
import org.innovateuk.ifs.address.repository.AddressTypeRepository;
import org.innovateuk.ifs.address.resource.AddressResource;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.invite.domain.ProjectUserInvite;
import org.innovateuk.ifs.invite.mapper.ProjectUserInviteMapper;
import org.innovateuk.ifs.invite.repository.ProjectUserInviteRepository;
import org.innovateuk.ifs.invite.resource.ProjectUserInviteResource;
import org.innovateuk.ifs.notifications.resource.Notification;
import org.innovateuk.ifs.notifications.resource.NotificationTarget;
import org.innovateuk.ifs.notifications.resource.SystemNotificationSource;
import org.innovateuk.ifs.notifications.resource.UserNotificationTarget;
import org.innovateuk.ifs.notifications.service.NotificationService;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.domain.OrganisationAddress;
import org.innovateuk.ifs.organisation.domain.OrganisationType;
import org.innovateuk.ifs.organisation.repository.OrganisationAddressRepository;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.project.constant.ProjectActivityStates;
import org.innovateuk.ifs.project.core.builder.ProjectBuilder;
import org.innovateuk.ifs.project.core.domain.PartnerOrganisation;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.innovateuk.ifs.project.core.mapper.ProjectUserMapper;
import org.innovateuk.ifs.project.core.repository.PartnerOrganisationRepository;
import org.innovateuk.ifs.project.core.repository.ProjectRepository;
import org.innovateuk.ifs.project.core.repository.ProjectUserRepository;
import org.innovateuk.ifs.project.core.workflow.configuration.ProjectWorkflowHandler;
import org.innovateuk.ifs.project.monitoringofficer.domain.LegacyMonitoringOfficer;
import org.innovateuk.ifs.project.monitoringofficer.repository.LegacyMonitoringOfficerRepository;
import org.innovateuk.ifs.project.projectdetails.workflow.configuration.ProjectDetailsWorkflowHandler;
import org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId;
import org.innovateuk.ifs.project.resource.ProjectState;
import org.innovateuk.ifs.project.resource.ProjectUserResource;
import org.innovateuk.ifs.project.spendprofile.builder.SpendProfileBuilder;
import org.innovateuk.ifs.project.spendprofile.domain.SpendProfile;
import org.innovateuk.ifs.project.spendprofile.repository.SpendProfileRepository;
import org.innovateuk.ifs.project.status.transactional.StatusService;
import org.innovateuk.ifs.security.LoggedInUserSupplier;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.ProcessRoleRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.Role;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.http.HttpStatus;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.address.builder.AddressBuilder.newAddress;
import static org.innovateuk.ifs.address.builder.AddressResourceBuilder.newAddressResource;
import static org.innovateuk.ifs.address.builder.AddressTypeBuilder.newAddressType;
import static org.innovateuk.ifs.address.resource.OrganisationAddressType.PROJECT;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.commons.validation.ValidationConstants.MAX_POSTCODE_LENGTH;
import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry;
import static org.innovateuk.ifs.invite.builder.ProjectUserInviteBuilder.newProjectUserInvite;
import static org.innovateuk.ifs.invite.builder.ProjectUserInviteResourceBuilder.newProjectUserInviteResource;
import static org.innovateuk.ifs.notifications.resource.NotificationMedium.EMAIL;
import static org.innovateuk.ifs.organisation.builder.OrganisationAddressBuilder.newOrganisationAddress;
import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation;
import static org.innovateuk.ifs.organisation.builder.OrganisationTypeBuilder.newOrganisationType;
import static org.innovateuk.ifs.project.builder.ProjectStatusResourceBuilder.newProjectStatusResource;
import static org.innovateuk.ifs.project.builder.ProjectUserResourceBuilder.newProjectUserResource;
import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject;
import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser;
import static org.innovateuk.ifs.project.core.domain.ProjectParticipantRole.*;
import static org.innovateuk.ifs.project.resource.ProjectState.WITHDRAWN;
import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole;
import static org.innovateuk.ifs.user.builder.UserBuilder.newUser;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
public class ProjectDetailsServiceImplTest extends BaseServiceUnitTest<ProjectDetailsService> {
@Mock
private NotificationService notificationService;
@Mock
private ApplicationRepository applicationRepositoryMock;
@Mock
private OrganisationRepository organisationRepositoryMock;
@Mock
private ProjectRepository projectRepositoryMock;
@Mock
private LoggedInUserSupplier loggedInUserSupplierMock;
@Mock
private ProjectUserMapper projectUserMapperMock;
@Mock
private ProjectUserRepository projectUserRepositoryMock;
@Mock
private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandlerMock;
@Mock
private SpendProfileRepository spendProfileRepositoryMock;
@Mock
private ProjectWorkflowHandler projectWorkflowHandlerMock;
@Mock
private ProjectUserInviteRepository projectUserInviteRepositoryMock;
@Mock
private ProcessRoleRepository processRoleRepositoryMock;
@Mock
private LegacyMonitoringOfficerRepository monitoringOfficerRepositoryMock;
@Mock
private PartnerOrganisationRepository partnerOrganisationRepositoryMock;
@Mock
private ProjectUserInviteMapper projectInviteMapperMock;
@Mock
private UserRepository userRepositoryMock;
@Mock
private AddressRepository addressRepositoryMock;
@Mock
private AddressMapper addressMapperMock;
@Mock
private OrganisationAddressRepository organisationAddressRepositoryMock;
@Mock
private AddressTypeRepository addressTypeRepositoryMock;
@Mock
private SystemNotificationSource systemNotificationSource;
private Long projectId = 123L;
private Long applicationId = 456L;
private Long userId = 7L;
private Long otherUserId = 8L;
private Application application;
private Organisation organisation;
private User user;
private ProcessRole leadApplicantProcessRole;
private ProjectUser leadPartnerProjectUser;
private Organisation o;
private Project project;
private static final String webBaseUrl = "https://ifs-local-dev/dashboard";
@Before
public void setUp() {
organisation = newOrganisation().
withOrganisationType(OrganisationTypeEnum.BUSINESS).
build();
user = newUser().
withId(userId).
build();
leadApplicantProcessRole = newProcessRole().
withOrganisationId(organisation.getId()).
withRole(Role.LEADAPPLICANT).
withUser(user).
build();
leadPartnerProjectUser = newProjectUser().
withOrganisation(organisation).
withRole(PROJECT_PARTNER).
withUser(user).
build();
application = newApplication().
withId(applicationId).
withProcessRoles(leadApplicantProcessRole).
withName("My Application").
withDurationInMonths(5L).
withStartDate(LocalDate.of(2017, 3, 2)).
build();
project = newProject().
withId(projectId).
withApplication(application).
withProjectUsers(singletonList(leadPartnerProjectUser)).
withGrantOfferLetter(null).
build();
OrganisationType businessOrganisationType = newOrganisationType().withOrganisationType(OrganisationTypeEnum.BUSINESS).build();
o = organisation;
o.setOrganisationType(businessOrganisationType);
when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application));
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(loggedInUserSupplierMock.get()).thenReturn(newUser().build());
setLoggedInUser(newUserResource().withId(user.getId()).build());
}
@Test
public void getProjectManager() {
final Long projectId = 123L;
final Project project = newProject().withId(projectId).build();
final ProjectUser projectManager = newProjectUser().withProject(project).withRole(PROJECT_MANAGER).build();
final ProjectUserResource projectManagerResource = newProjectUserResource().withProject(projectId).withRoleName(PROJECT_MANAGER.getName()).build();
when(projectUserMapperMock.mapToResource(projectManager)).thenReturn(projectManagerResource);
when(projectUserRepositoryMock.findByProjectIdAndRole(projectId, PROJECT_MANAGER)).thenReturn(Optional.of(projectManager));
ServiceResult<ProjectUserResource> foundProjectManager = service.getProjectManager(projectId);
assertTrue(foundProjectManager.isSuccess());
assertTrue(foundProjectManager.getSuccess().getRoleName().equals(PROJECT_MANAGER.getName()));
assertTrue(foundProjectManager.getSuccess().getProject().equals(projectId));
}
@Test
public void invalidProjectManagerProvided() {
ServiceResult<Void> result = service.setProjectManager(projectId, otherUserId);
assertFalse(result.isSuccess());
assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_MUST_BE_LEAD_PARTNER));
}
@Test
public void setProjectManagerWhenGOLAlreadyGenerated() {
FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build();
Project existingProject = newProject().withId(projectId).withGrantOfferLetter(golFile).build();
assertTrue(existingProject.getProjectUsers().isEmpty());
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject));
ServiceResult<Void> result = service.setProjectManager(projectId, userId);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED));
assertTrue(existingProject.getProjectUsers().isEmpty());
}
@Test
public void validProjectManagerProvided() {
ServiceResult<Void> result = service.setProjectManager(projectId, userId);
assertTrue(result.isSuccess());
ProjectUser expectedProjectManager = newProjectUser().
withId().
withProject(project).
withOrganisation(organisation).
withRole(PROJECT_MANAGER).
withUser(user).
build();
assertEquals(expectedProjectManager, project.getProjectUsers().get(project.getProjectUsers().size() - 1));
}
@Test
public void validProjectManagerProvidedWithExistingProjectManager() {
User differentUser = newUser().build();
Organisation differentOrganisation = newOrganisation().build();
@SuppressWarnings("unused")
ProjectUser existingProjectManager = newProjectUser().
withId(456L).
withProject(project).
withRole(PROJECT_MANAGER).
withOrganisation(differentOrganisation).
withUser(differentUser).
build();
ServiceResult<Void> result = service.setProjectManager(projectId, userId);
assertTrue(result.isSuccess());
ProjectUser expectedProjectManager = newProjectUser().
withId(456L).
withProject(project).
withOrganisation(organisation).
withRole(PROJECT_MANAGER).
withUser(user).
build();
assertEquals(expectedProjectManager, project.getProjectUsers().get(project.getProjectUsers().size() - 1));
}
@Test
public void updateProjectStartDateButStartDateDoesntBeginOnFirstDayOfMonth() {
LocalDate now = LocalDate.now();
LocalDate dateNotOnFirstDayOfMonth = LocalDate.of(now.getYear(), now.getMonthValue(), 2).plusMonths(1);
Project existingProject = newProject().build();
assertNull(existingProject.getTargetStartDate());
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject));
ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, dateNotOnFirstDayOfMonth);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_DATE_MUST_START_ON_FIRST_DAY_OF_MONTH));
verify(projectRepositoryMock, never()).findById(123L);
assertNull(existingProject.getTargetStartDate());
}
@Test
public void updateProjectStartDateButStartDateNotInFuture() {
LocalDate now = LocalDate.now();
LocalDate pastDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).minusMonths(1);
Project existingProject = newProject().build();
assertNull(existingProject.getTargetStartDate());
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject));
ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, pastDate);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_DATE_MUST_BE_IN_THE_FUTURE));
verify(projectRepositoryMock, never()).findById(123L);
assertNull(existingProject.getTargetStartDate());
}
@Test
public void updateProjectStartDateWhenSpendProfileHasAlreadyBeenGenerated() {
LocalDate now = LocalDate.now();
LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1);
Project existingProject = newProject().build();
assertNull(existingProject.getTargetStartDate());
List<SpendProfile> spendProfiles = SpendProfileBuilder.newSpendProfile().build(2);
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject));
when(spendProfileRepositoryMock.findByProjectId(123L)).thenReturn(spendProfiles);
ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_START_DATE_CANNOT_BE_CHANGED_ONCE_SPEND_PROFILE_HAS_BEEN_GENERATED));
verify(projectRepositoryMock, never()).findById(123L);
verify(spendProfileRepositoryMock).findByProjectId(123L);
assertNull(existingProject.getTargetStartDate());
}
@Test
public void updateProjectStartDateButProjectDoesntExist() {
LocalDate now = LocalDate.now();
LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1);
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.empty());
ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(notFoundError(Project.class, 123L)));
}
@Test
public void updateProjectStartDateSuccess() {
LocalDate now = LocalDate.now();
LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1);
Project existingProject = newProject().build();
assertNull(existingProject.getTargetStartDate());
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject));
ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate);
assertTrue(updateResult.isSuccess());
verify(projectRepositoryMock).findById(123L);
assertEquals(validDate, existingProject.getTargetStartDate());
}
@Test
public void updateProjectDurationWhenDurationLessThanAMonth() {
long projectId = 123L;
ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 0L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_MUST_BE_MINIMUM_ONE_MONTH));
ServiceResult<Void> updateResult2 = service.updateProjectDuration(projectId, -3L);
assertTrue(updateResult2.isFailure());
assertTrue(updateResult2.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_MUST_BE_MINIMUM_ONE_MONTH));
}
@Test
public void updateProjectDurationWhenProjectDoesNotExist() {
long projectId = 123L;
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.empty());
ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(notFoundError(Project.class, 123L)));
}
@Test
public void updateProjectDurationWhenSpendProfileAlreadyGenerated() {
long projectId = 123L;
List<SpendProfile> spendProfiles = SpendProfileBuilder.newSpendProfile().build(2);
when(spendProfileRepositoryMock.findByProjectId(projectId)).thenReturn(spendProfiles);
ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_CANNOT_BE_CHANGED_ONCE_SPEND_PROFILE_HAS_BEEN_GENERATED));
}
@Test
public void updateProjectDurationWhenProjectIsAlreadyWithdrawn() {
long projectId = 123L;
Project existingProject = newProject().build();
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject));
when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(WITHDRAWN);
ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(GENERAL_FORBIDDEN));
}
@Test
public void updateProjectDurationSuccess() {
long projectId = 123L;
long durationInMonths = 36L;
Project existingProject = newProject().build();
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject));
ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, durationInMonths);
assertTrue(updateResult.isSuccess());
assertEquals(durationInMonths, (long) existingProject.getDurationInMonths());
}
@Test
public void updateFinanceContact() {
Project project = newProject().withId(123L).build();
Organisation organisation = newOrganisation().withId(5L).build();
User user = newUser().withId(7L).build();
newProjectUser().withOrganisation(organisation).withUser(user).withProject(project).withRole(PROJECT_PARTNER).build();
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project));
when(projectWorkflowHandlerMock.getState(project)).thenReturn(ProjectState.SETUP);
when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation));
setLoggedInUser(newUserResource().withId(user.getId()).build());
ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L);
assertTrue(updateResult.isSuccess());
List<ProjectUser> foundFinanceContacts = simpleFilter(project.getProjectUsers(), projectUser ->
projectUser.getOrganisation().equals(organisation) &&
projectUser.getUser().equals(user) &&
projectUser.getProcess().equals(project) &&
projectUser.getRole().equals(PROJECT_FINANCE_CONTACT));
assertEquals(1, foundFinanceContacts.size());
}
@Test
public void updateFinanceContactWhenGOLAlreadyGenerated() {
FileEntry golFileEntry = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build();
Project project = newProject()
.withId(123L)
.withGrantOfferLetter(golFileEntry)
.build();
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project));
ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED));
verify(processRoleRepositoryMock, never()).save(isA(ProcessRole.class));
}
@Test
public void updateFinanceContactButUserIsNotExistingPartner() {
Project project = newProject().withId(123L).build();
Organisation organisation = newOrganisation().withId(5L).build();
User user = newUser().withId(7L).build();
newProjectUser().withOrganisation(organisation).withUser(user).withProject(project).withRole(PROJECT_MANAGER).build();
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project));
when(projectWorkflowHandlerMock.getState(project)).thenReturn(ProjectState.SETUP);
when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation));
ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_MUST_BE_A_PARTNER_ON_THE_PROJECT_FOR_THE_ORGANISATION));
verify(processRoleRepositoryMock, never()).save(isA(ProcessRole.class));
}
@Test
public void updateFinanceContactWhenNotPresentOnTheProject() {
long userIdForUserNotOnProject = 6L;
Project existingProject = newProject().withId(123L).build();
Project anotherProject = newProject().withId(9999L).build();
when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject));
when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(ProjectState.SETUP);
Organisation organisation = newOrganisation().withId(5L).build();
when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation));
User user = newUser().withId(7L).build();
newProjectUser().withOrganisation(organisation).withUser(user).withProject(anotherProject).withRole(PROJECT_PARTNER).build();
ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), userIdForUserNotOnProject);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_MUST_BE_A_USER_ON_THE_PROJECT_FOR_THE_ORGANISATION));
}
@Test
public void updateFinanceContactAllowedWhenFinanceContactAlreadySet() {
User anotherUser = newUser().build();
Project existingProject = newProject().build();
when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject));
when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(ProjectState.SETUP);
Organisation organisation = newOrganisation().build();
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
newProjectUser().
withOrganisation(organisation).
withUser(user, anotherUser).
withProject(existingProject).
withRole(PROJECT_FINANCE_CONTACT, PROJECT_PARTNER).build(2);
setLoggedInUser(newUserResource().withId(user.getId()).build());
ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(existingProject.getId(), organisation.getId()), anotherUser.getId());
assertTrue(updateResult.isSuccess());
List<ProjectUser> organisationFinanceContacts = existingProject.getProjectUsers(pu -> pu.getRole().equals(PROJECT_FINANCE_CONTACT) &&
pu.getOrganisation().equals(organisation));
assertEquals(1, organisationFinanceContacts.size());
assertEquals(anotherUser, organisationFinanceContacts.get(0).getUser());
}
@Test
public void updatePartnerProjectLocationWhenPostcodeIsNullOrEmpty() {
long projectId = 1L;
long organisationId = 2L;
String postcode = null;
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST)));
postcode = "";
updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST)));
postcode = " ";
updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST)));
}
@Test
public void updatePartnerProjectLocationWhenPostcodeEnteredExceedsMaxLength() {
long projectId = 1L;
long organisationId = 2L;
String postcode = "SOME LONG POSTCODE";
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(new Error("validation.field.too.many.characters", asList("", MAX_POSTCODE_LENGTH), HttpStatus.BAD_REQUEST)));
}
@Test
public void updatePartnerProjectLocationWhenMonitoringOfficerAssigned() {
long projectId = 1L;
long organisationId = 2L;
String postcode = "TW14 9QG";
Project existingProject = newProject().withId(projectId).withGrantOfferLetter(newFileEntry().build()).build();
when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject));
when(monitoringOfficerRepositoryMock.findOneByProjectId(projectId)).thenReturn(new LegacyMonitoringOfficer());
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(PROJECT_SETUP_LOCATION_CANNOT_BE_UPDATED_IF_GOL_GENERATED));
}
@Test
public void updatePartnerProjectLocationWhenPartnerOrganisationDoesNotExist() {
long projectId = 1L;
long organisationId = 2L;
String postcode = "TW14 9QG";
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
Project existingProject = newProject().withId(projectId).build();
when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject));
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isFailure());
assertTrue(updateResult.getFailure().is(notFoundError(PartnerOrganisation.class, projectId, organisationId)));
}
@Test
public void updatePartnerProjectLocationEnsureLowerCasePostcodeIsSavedAsUpperCase() {
long projectId = 1L;
long organisationId = 2L;
String postcode = "tw14 9qg";
PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation();
Project existingProject = newProject().withId(projectId).build();
when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject));
when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb);
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isSuccess());
assertEquals(postcode.toUpperCase(), partnerOrganisationInDb.getPostcode());
}
@Test
public void updatePartnerProjectLocationSuccess() {
long projectId = 1L;
long organisationId = 2L;
String postcode = "UB7 8QF";
PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(project, null, true);
Project existingProject = newProject().withId(projectId).build();
when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject));
when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb);
when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user));
ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId);
ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcode);
assertTrue(updateResult.isSuccess());
assertEquals(postcode, partnerOrganisationInDb.getPostcode());
verify(projectDetailsWorkflowHandlerMock).projectLocationAdded(eq(project), eq(leadPartnerProjectUser));
}
@Test
public void inviteProjectManagerWhenProjectNotInDB() {
Long projectId = 1L;
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(17L)
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(newProjectUserInvite().withEmail("a@b.com").withName("A B").build());
when(projectRepositoryMock.findById(projectId)).thenThrow(new IllegalArgumentException());
ServiceResult<Void> result = null;
try {
result = service.inviteProjectManager(projectId, inviteResource);
} catch (Exception e) {
// We expect an exception to be thrown
assertTrue(e instanceof IllegalArgumentException);
assertNull(result);
verify(notificationService, never()).sendNotificationWithFlush(any(Notification.class), eq(EMAIL));
// This exception flow is the only expected flow, so return from here and assertFalse if no exception
return;
}
// Should not reach here - we must get an exception
assertFalse(true);
}
@Test
public void inviteProjectManagerWhenGOLAlreadyGenerated() {
Long projectId = 1L;
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.build();
FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build();
Project projectInDB = ProjectBuilder.newProject()
.withId(projectId)
.withGrantOfferLetter(golFile)
.build();
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB));
ServiceResult<Void> result = service.inviteProjectManager(projectId, inviteResource);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED));
}
@Test
public void inviteProjectManagerWhenUnableToSendNotification() {
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withCompetitionName("Competition 1")
.withApplicationId(application.getId())
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(organisation.getId())
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
Project projectInDB = ProjectBuilder.newProject()
.withName("Project 1")
.withApplication(application)
.build();
when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB));
NotificationTarget to = new UserNotificationTarget("A B", "a@b.com");
Map<String, Object> globalArguments = new HashMap<>();
globalArguments.put("projectName", projectInDB.getName());
globalArguments.put("competitionName", "Competition 1");
globalArguments.put("leadOrganisation", organisation.getName());
globalArguments.put("applicationId", application.getId());
globalArguments.put("inviteOrganisationName", "Invite Organisation 1");
globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash());
Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_PROJECT_MANAGER, globalArguments);
when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(
serviceFailure(new Error(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE)));
ProjectUserInvite projectInvite = newProjectUserInvite()
.withEmail("a@b.com")
.withName("A B")
.build();
when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite);
ServiceResult<Void> result = service.inviteProjectManager(projectInDB.getId(), inviteResource);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE));
verify(projectUserInviteRepositoryMock).save(projectInvite);
}
@Test
public void inviteProjectManagerSuccess() {
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withCompetitionName("Competition 1")
.withApplicationId(application.getId())
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(organisation.getId())
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
Project projectInDB = ProjectBuilder.newProject()
.withName("Project 1")
.withApplication(application)
.build();
when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB));
NotificationTarget to = new UserNotificationTarget("A B", "a@b.com");
Map<String, Object> globalArguments = new HashMap<>();
globalArguments.put("projectName", projectInDB.getName());
globalArguments.put("competitionName", "Competition 1");
globalArguments.put("leadOrganisation", organisation.getName());
globalArguments.put("applicationId", application.getId());
globalArguments.put("inviteOrganisationName", "Invite Organisation 1");
globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash());
Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_PROJECT_MANAGER, globalArguments);
when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess());
ProjectUserInvite projectInvite = newProjectUserInvite().
withEmail("a@b.com").
withName("A B").
build();
when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite);
ServiceResult<Void> result = service.inviteProjectManager(projectInDB.getId(), inviteResource);
assertTrue(result.isSuccess());
verify(notificationService).sendNotificationWithFlush(notification, EMAIL);
verify(projectUserInviteRepositoryMock).save(projectInvite);
}
@Test
public void inviteFinanceContactWhenGOLAlreadyGenerated() {
Long projectId = 1L;
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(17L)
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
FileEntry golFileEntry = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build();
Project projectInDB = ProjectBuilder.newProject()
.withId(projectId)
.withGrantOfferLetter(golFileEntry)
.build();
when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB));
ServiceResult<Void> result = service.inviteFinanceContact(projectId, inviteResource);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED));
}
@Test
public void inviteFinanceContactSuccess() {
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withCompetitionName("Competition 1")
.withApplicationId(application.getId())
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(organisation.getId())
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
Project projectInDB = ProjectBuilder.newProject()
.withName("Project 1")
.withApplication(application)
.build();
NotificationTarget to = new UserNotificationTarget("A B", "a@b.com");
when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB));
Map<String, Object> globalArguments = new HashMap<>();
globalArguments.put("projectName", projectInDB.getName());
globalArguments.put("competitionName", "Competition 1");
globalArguments.put("leadOrganisation", organisation.getName());
globalArguments.put("applicationId", application.getId());
globalArguments.put("inviteOrganisationName", "Invite Organisation 1");
globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash());
Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_FINANCE_CONTACT, globalArguments);
when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess());
ProjectUserInvite projectInvite = newProjectUserInvite()
.withName("A B")
.withEmail("a@b.com")
.build();
when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite);
ServiceResult<Void> result = service.inviteFinanceContact(projectInDB.getId(), inviteResource);
assertTrue(result.isSuccess());
verify(notificationService).sendNotificationWithFlush(notification, EMAIL);
verify(projectUserInviteRepositoryMock).save(projectInvite);
}
@Test
public void updateProjectAddressToBeRegisteredAddress() {
AddressResource existingRegisteredAddressResource = newAddressResource().build();
Address registeredAddress = newAddress().build();
when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user));
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(addressRepositoryMock.existsById(existingRegisteredAddressResource.getId())).thenReturn(true);
when(addressRepositoryMock.findById(existingRegisteredAddressResource.getId())).thenReturn(Optional.of(registeredAddress));
setLoggedInUser(newUserResource().withId(user.getId()).build());
assertNull(project.getAddress());
ServiceResult<Void> result = service.updateProjectAddress(organisation.getId(), project.getId(), existingRegisteredAddressResource);
assertTrue(result.isSuccess());
assertEquals(registeredAddress, project.getAddress());
}
@Test
public void updateProjectAddressToBeOperatingAddress() {
AddressResource existingOperatingAddressResource = newAddressResource().build();
Address operatingAddress = newAddress().build();
when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user));
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(addressRepositoryMock.existsById(existingOperatingAddressResource.getId())).thenReturn(true);
when(addressRepositoryMock.findById(existingOperatingAddressResource.getId())).thenReturn(Optional.of(operatingAddress));
setLoggedInUser(newUserResource().withId(user.getId()).build());
assertNull(project.getAddress());
ServiceResult<Void> result = service.updateProjectAddress(organisation.getId(), project.getId(), existingOperatingAddressResource);
assertTrue(result.isSuccess());
assertEquals(operatingAddress, project.getAddress());
}
@Test
public void updateProjectAddressToNewProjectAddress() {
Organisation leadOrganisation = newOrganisation()
.withId(organisation.getId())
.build();
AddressResource newAddressResource = newAddressResource().build();
Address newAddress = newAddress()
.build();
AddressType projectAddressType = newAddressType()
.withId((long) PROJECT.getOrdinal())
.withName(PROJECT.name())
.build();
OrganisationAddress organisationAddress = newOrganisationAddress()
.withOrganisation(leadOrganisation)
.withAddress(newAddress).withAddressType(projectAddressType)
.build();
when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user));
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(addressRepositoryMock.existsById(newAddressResource.getId())).thenReturn(false);
when(addressMapperMock.mapToDomain(newAddressResource)).thenReturn(newAddress);
when(addressTypeRepositoryMock.findById(PROJECT.getOrdinal())).thenReturn(Optional.of(projectAddressType));
when(organisationAddressRepositoryMock.findByOrganisationIdAndAddressType(leadOrganisation.getId(), projectAddressType)).thenReturn(emptyList());
when(organisationAddressRepositoryMock.save(organisationAddress)).thenReturn(organisationAddress);
when(projectDetailsWorkflowHandlerMock.projectAddressAdded(project, leadPartnerProjectUser)).thenReturn(true);
setLoggedInUser(newUserResource().withId(user.getId()).build());
assertNull(project.getAddress());
ServiceResult<Void> result = service.updateProjectAddress(leadOrganisation.getId(), project.getId(), newAddressResource);
assertTrue(result.isSuccess());
verify(organisationAddressRepositoryMock, never()).delete(Mockito.any(OrganisationAddress.class));
assertEquals(newAddress, project.getAddress());
}
@Test
public void updateProjectAddressToNewProjectAddressAndExistingAddressAssociatedWithOrg() {
Organisation leadOrganisation = newOrganisation().withId(organisation.getId()).build();
AddressResource newAddressResource = newAddressResource().build();
Address newAddress = newAddress().build();
AddressType projectAddressType = newAddressType().withId((long) PROJECT.getOrdinal()).withName(PROJECT.name()).build();
OrganisationAddress organisationAddress = newOrganisationAddress().withOrganisation(leadOrganisation).withAddress(newAddress).withAddressType(projectAddressType).build();
when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user));
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(addressRepositoryMock.existsById(newAddressResource.getId())).thenReturn(false);
when(addressMapperMock.mapToDomain(newAddressResource)).thenReturn(newAddress);
when(addressTypeRepositoryMock.findById(PROJECT.getOrdinal())).thenReturn(Optional.of(projectAddressType));
when(organisationAddressRepositoryMock.findByOrganisationIdAndAddressType(leadOrganisation.getId(), projectAddressType)).thenReturn(singletonList(organisationAddress));
when(organisationAddressRepositoryMock.save(organisationAddress)).thenReturn(organisationAddress);
when(projectDetailsWorkflowHandlerMock.projectAddressAdded(project, leadPartnerProjectUser)).thenReturn(true);
setLoggedInUser(newUserResource().withId(user.getId()).build());
assertNull(project.getAddress());
ServiceResult<Void> result = service.updateProjectAddress(leadOrganisation.getId(), project.getId(), newAddressResource);
assertTrue(result.isSuccess());
assertEquals(newAddress, project.getAddress());
}
@Test
public void inviteProjectFinanceUser(){
ProjectUserInviteResource inviteResource = newProjectUserInviteResource()
.withCompetitionName("Competition 1")
.withApplicationId(application.getId())
.withName("Abc Xyz")
.withEmail("Abc.xyz@gmail.com")
.withLeadOrganisation(organisation.getId())
.withOrganisationName("Invite Organisation 1")
.withHash("sample/url")
.build();
ProcessRole[] roles = newProcessRole()
.withOrganisationId(organisation.getId())
.withRole(Role.LEADAPPLICANT)
.build(1)
.toArray(new ProcessRole[0]);
Application a = newApplication()
.withProcessRoles(roles)
.build();
Project projectInDB = ProjectBuilder.newProject()
.withName("Project 1")
.withApplication(a)
.build();
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB));
NotificationTarget to = new UserNotificationTarget("A B", "a@b.com");
Map<String, Object> globalArguments = new HashMap<>();
globalArguments.put("projectName", projectInDB.getName());
globalArguments.put("competitionName", "Competition 1");
globalArguments.put("leadOrganisation", organisation.getName());
globalArguments.put("applicationId", application.getId());
globalArguments.put("inviteOrganisationName", "Invite Organisation 1");
globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash());
Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_FINANCE_CONTACT, globalArguments);
when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess());
ProjectUserInvite projectInvite = newProjectUserInvite()
.withEmail("a@b.com")
.withName("A B")
.build();
when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite);
ServiceResult<Void> success = service.inviteFinanceContact(projectInDB.getId(), inviteResource);
assertTrue(success.isSuccess());
verify(notificationService).sendNotificationWithFlush(notification, EMAIL);
verify(projectUserInviteRepositoryMock).save(projectInvite);
verify(projectInviteMapperMock).mapToDomain(inviteResource);
}
@Override
protected ProjectDetailsService supplyServiceUnderTest() {
ProjectDetailsServiceImpl projectDetailsService = new ProjectDetailsServiceImpl();
ReflectionTestUtils.setField(projectDetailsService, "webBaseUrl", webBaseUrl);
return projectDetailsService;
}
}
|
package org.opencb.opencga.storage.core.variant.adaptors.sample;
import org.opencb.biodata.models.feature.Genotype;
import org.opencb.biodata.models.variant.StudyEntry;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.FileEntry;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryResult;
import org.opencb.opencga.core.results.VariantQueryResult;
import org.opencb.opencga.storage.core.metadata.VariantStorageMetadataManager;
import org.opencb.opencga.storage.core.variant.adaptors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class VariantSampleDataManager {
public static final String SAMPLE_BATCH_SIZE = "sampleBatchSize";
public static final int SAMPLE_BATCH_SIZE_DEFAULT = 1000;
private final VariantDBAdaptor dbAdaptor;
private final VariantStorageMetadataManager metadataManager;
private final Map<String, String> normalizeGt = new HashMap<>();
private final Logger logger = LoggerFactory.getLogger(VariantSampleDataManager.class);
public VariantSampleDataManager(VariantDBAdaptor dbAdaptor) {
this.dbAdaptor = dbAdaptor;
this.metadataManager = dbAdaptor.getMetadataManager();
}
public QueryResult<VariantSampleData> getSampleData(String variant, String study, QueryOptions options) {
options = options == null ? new QueryOptions() : options;
int sampleLimit = options.getInt(SAMPLE_BATCH_SIZE, SAMPLE_BATCH_SIZE_DEFAULT);
return getSampleData(variant, study, options, sampleLimit);
}
public QueryResult<VariantSampleData> getSampleData(String variant, String study, QueryOptions options, int sampleLimit) {
options = options == null ? new QueryOptions() : options;
Set<String> genotypes = new HashSet<>(options.getAsStringList(VariantQueryParam.GENOTYPE.key()));
if (genotypes.isEmpty()) {
genotypes.add("0/1");
genotypes.add("1/1");
}
boolean merge = options.getBoolean("merge", false);
return getSampleData(variant, study, options, genotypes, merge, sampleLimit);
}
public QueryResult<VariantSampleData> getSampleData(String variant, String study, QueryOptions options,
Set<String> genotypes, boolean merge, int sampleLimit) {
options = options == null ? new QueryOptions() : options;
int studyId = metadataManager.getStudyId(study);
int skip = Math.max(0, options.getInt(QueryOptions.SKIP, 0));
int limit = Math.max(0, options.getInt(QueryOptions.LIMIT, 10));
int dbTime = 0;
Map<String, Integer> gtCountMap = new HashMap<>();
Map<String, List<SampleData>> gtMap = new HashMap<>();
Map<String, FileEntry> files = new HashMap<>();
for (String gt : merge ? Collections.singleton(VariantQueryUtils.ALL) : genotypes) {
gtCountMap.put(gt, 0);
gtMap.put(gt, new ArrayList<>(limit));
}
int sampleSkip = 0;
int readSamples = 0;
int queries = 0;
while (true) {
Query query = new Query(VariantQueryParam.ID.key(), variant)
.append(VariantQueryParam.STUDY.key(), study)
.append(VariantQueryParam.SAMPLE_LIMIT.key(), sampleLimit)
.append(VariantQueryParam.SAMPLE_SKIP.key(), sampleSkip);
sampleSkip += sampleLimit;
QueryOptions variantQueryOptions = new QueryOptions(QueryOptions.EXCLUDE,
Arrays.asList(VariantField.ANNOTATION, VariantField.STUDIES_STATS));
VariantQueryResult<Variant> result = dbAdaptor.get(query, variantQueryOptions);
if (result.getNumResults() == 0) {
throw VariantQueryException.variantNotFound(variant);
}
dbTime += result.getDbTime();
queries++;
Variant v = result.first();
StudyEntry studyEntry = v.getStudies().get(0);
List<String> samples = studyEntry.getOrderedSamplesName();
readSamples += samples.size();
for (String sample : samples) {
Map<String, String> sampleDataAsMap = studyEntry.getSampleDataAsMap(sample);
String gt = normalizeGt(sampleDataAsMap.getOrDefault("GT", GenotypeClass.NA_GT_VALUE));
if (genotypes.contains(gt)) {
// Skip other genotypes
if (merge) {
// Merge after filtering by genotype
gt = VariantQueryUtils.ALL;
}
List<SampleData> gtList = gtMap.get(gt);
if (gtCountMap.merge(gt, 1, Integer::sum) > skip) {
if (gtList.size() < limit) {
Integer sampleId = metadataManager.getSampleId(studyId, sample);
FileEntry fileEntry = null;
for (Integer fileId : metadataManager.getFileIdsFromSampleIds(studyId, Collections.singleton(sampleId))) {
String fileName = metadataManager.getFileName(studyId, fileId);
fileEntry = studyEntry.getFile(fileName);
break;
}
if (fileEntry == null) {
List<String> fileNames = new LinkedList<>();
for (Integer fileId : metadataManager.getFileIdsFromSampleIds(studyId, Collections.singleton(sampleId))) {
fileNames.add(metadataManager.getFileName(studyId, fileId));
}
throw new VariantQueryException("No file found for sample '" + sample + "', expected any of " + fileNames);
}
SampleData sampleData = new SampleData(sample, sampleDataAsMap, fileEntry.getFileId());
files.put(fileEntry.getFileId(), fileEntry);
gtList.add(sampleData);
}
}
}
}
if (samples.size() < sampleLimit) {
// logger.debug("Exit end samples");
break;
}
if (gtMap.values().stream().allMatch(c -> c.size() >= limit)) {
// logger.debug("Exit limit");
break;
}
}
return new QueryResult<>(variant, dbTime, 1, 1, "Queries : " + queries + " , readSamples : " + readSamples, null,
Collections.singletonList(new VariantSampleData(variant, study, gtMap, files)));
}
protected String normalizeGt(String gt) {
if (gt.contains("|")) {
return normalizeGt.computeIfAbsent(gt, k -> {
Genotype genotype = new Genotype(k.replace('|', '/'));
genotype.normalizeAllelesIdx();
return genotype.toString();
});
}
return gt;
}
}
|
package editor;
import editor.util.EditorUtilities;
import editor.util.Project;
import gw.config.CommonServices;
import gw.config.IPlatformHelper;
import gw.lang.Gosu;
import gw.lang.gosuc.GosucDependency;
import gw.lang.gosuc.GosucModule;
import gw.lang.init.GosuInitialization;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.module.IExecutionEnvironment;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
public class RunMe
{
private static BasicGosuEditor _gosuEditor;
private static GosuInitialization _gosuInitialization;
public static void main( String[] args ) throws Exception
{
launchEditor();
}
public static BasicGosuEditor getEditorFrame()
{
return _gosuEditor;
}
public static void launchEditor() throws Exception
{
EventQueue.invokeLater(
() -> {
_gosuEditor = BasicGosuEditor.create();
_gosuEditor.restoreState( EditorUtilities.getRecentProject( _gosuEditor.getGosuPanel() ) );
_gosuEditor.showMe();
} );
}
public static void reinitializeGosu( Project project )
{
CommonServices.getKernel().redefineService_Privileged( IPlatformHelper.class, new GosuEditorPlatformHelper() );
IExecutionEnvironment execEnv = TypeSystem.getExecutionEnvironment();
_gosuInitialization = GosuInitialization.instance( execEnv );
GosucModule gosucModule = new GosucModule(
IExecutionEnvironment.DEFAULT_SINGLE_MODULE_NAME, project.getSourcePath(), deriveClasspath( project ),
"", Collections.<GosucDependency>emptyList(), Collections.<String>emptyList() );
_gosuInitialization.reinitializeSimpleIde( gosucModule );
}
private static List<String> deriveClasspath( Project project )
{
List<String> classpath = new ArrayList<>();
List<String> sourcePath = project.getSourcePath();
for( String path: sourcePath )
{
if( !path.toLowerCase().startsWith( project.getProjectDir().getAbsolutePath().toLowerCase() ) )
{
classpath.add( path );
}
}
List<String> collect = Gosu.deriveClasspathFrom( RunMe.class ).stream().map( File::getAbsolutePath ).collect( Collectors.toList() );
classpath.addAll( collect );
return classpath;
}
}
|
package bot;
import io.datawire.quark.netty.QuarkNettyRuntime;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import slack.SlackClient;
import slack.SlackHandler;
import slack.event.ChannelArchive;
import slack.event.ChannelCreated;
import slack.event.ChannelDeleted;
import slack.event.ChannelHistoryChanged;
import slack.event.ChannelJoined;
import slack.event.ChannelLeft;
import slack.event.ChannelMarked;
import slack.event.ChannelRename;
import slack.event.ChannelUnarchive;
import slack.event.Hello;
import slack.event.Message;
import slack.event.MessageSent;
import slack.event.SlackError;
import slack.event.SlackEvent;
import slack.event.UserTyping;
public class SlackBot implements SlackHandler {
public static void main(String[] args) throws Exception {
QuarkNettyRuntime runtime = QuarkNettyRuntime.getRuntime();
SlackClient client = new SlackClient(runtime, getToken());
client.subscribe(new SlackBot());
}
private static String getToken() throws Exception {
try {
String token = new String(Files.readAllBytes(Paths.get(".slack.token").toAbsolutePath()), StandardCharsets.UTF_8);
return token.replaceFirst("\r", "").replaceFirst("\n", "");
} catch (NoSuchFileException fnfe) {
throw new Exception("You can generate a token at https://api.slack.com/web", fnfe);
}
}
@Override
public void onSlackEvent(SlackEvent event) {
// TODO Auto-generated method stub
}
private void print(SlackEvent evt, String...objects) {
StringBuilder b = new StringBuilder();
if (evt.timestamp != null) {
b.append(evt.timestamp);
}
if (evt.channel != null) {
b.append(" ").append(evt.channel.channel);
}
b.append(":");
for (String o : objects) {
b.append(" ").append(o != null ? o : "null");
}
System.out.println(b.toString());
}
@Override
public void onHello(Hello hello) {
print(hello, hello.type);
}
@Override
public void onSlackError(SlackError error) {
print(error, error.text, error.code.toString());
}
@Override
public void onMessage(Message message) {
print(message, message.text);
if (message.text != null && message.text.indexOf("java quark") > -1 ) {
message.channel.send("java quarkbot: " + message.text);
}
}
@Override
public void onMessageSent(MessageSent sent) {
// TODO Auto-generated method stub
}
@Override
public void onUserTyping(UserTyping typing) {
// TODO Auto-generated method stub
}
@Override
public void onChannelMarked(ChannelMarked marked) {
// TODO Auto-generated method stub
}
@Override
public void onChannelCreated(ChannelCreated created) {
// TODO Auto-generated method stub
}
@Override
public void onChannelJoined(ChannelJoined joined) {
// TODO Auto-generated method stub
}
@Override
public void onChannelLeft(ChannelLeft left) {
// TODO Auto-generated method stub
}
@Override
public void onChannelDeleted(ChannelDeleted deleted) {
// TODO Auto-generated method stub
}
@Override
public void onChannelRename(ChannelRename renamed) {
// TODO Auto-generated method stub
}
@Override
public void onChannelArchive(ChannelArchive archived) {
// TODO Auto-generated method stub
}
@Override
public void onChannelUnarchive(ChannelUnarchive unarchived) {
// TODO Auto-generated method stub
}
@Override
public void onChannelHistoryChanged(ChannelHistoryChanged historyChanged) {
// TODO Auto-generated method stub
}
}
|
package org.neon_lang.jnex;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.nevec.rjm.BigDecimalMath;
class Executor {
private final boolean enable_assert = true;
private class ActivationFrame {
int nesting_depth;
ActivationFrame outer;
Cell[] locals;
int opstack_depth;
ActivationFrame(int nesting_depth, ActivationFrame outer, int count, int opstack_depth)
{
this.nesting_depth = nesting_depth;
this.outer = outer;
locals = new Cell[count];
for (int i = 0; i < count; i++) {
locals[i] = new Cell();
}
this.opstack_depth = opstack_depth;
}
}
Executor(DataInput in, String[] args)
{
predefined = new HashMap<String, GenericFunction>();
predefined.put("array__append", this::array__append);
predefined.put("array__concat", this::array__concat);
predefined.put("array__extend", this::array__extend);
predefined.put("array__find", this::array__find);
predefined.put("array__remove", this::array__remove);
predefined.put("array__reversed", this::array__reversed);
predefined.put("array__size", this::array__size);
predefined.put("array__slice", this::array__slice);
predefined.put("array__splice", this::array__splice);
predefined.put("array__toBytes__number", this::array__toBytes__number);
predefined.put("array__toString__number", this::array__toString__number);
predefined.put("array__toString__string", this::array__toString__string);
predefined.put("array__toString__object", this::array__toString__object);
predefined.put("boolean__toString", this::boolean__toString);
predefined.put("bytes__decodeToString", this::bytes__decodeToString);
predefined.put("bytes__index", this::bytes__index);
predefined.put("bytes__range", this::bytes__range);
predefined.put("bytes__size", this::bytes__size);
predefined.put("bytes__splice", this::bytes__splice);
predefined.put("bytes__toArray", this::bytes__toArray);
predefined.put("bytes__toString", this::bytes__toString);
predefined.put("dictionary__keys", this::dictionary__keys);
predefined.put("dictionary__remove", this::dictionary__remove);
predefined.put("exceptiontype__toString", this::exceptiontype__toString);
predefined.put("num", this::num);
predefined.put("number__toString", this::number__toString);
predefined.put("object__getArray", this::object__getArray);
predefined.put("object__getBoolean", this::object__getBoolean);
predefined.put("object__getBytes", this::object__getBytes);
predefined.put("object__getDictionary", this::object__getDictionary);
predefined.put("object__getNumber", this::object__getNumber);
predefined.put("object__getString", this::object__getString);
predefined.put("object__invokeMethod", this::object__invokeMethod);
predefined.put("object__isNull", this::object__isNull);
predefined.put("object__makeArray", this::object__makeArray);
predefined.put("object__makeBoolean", this::object__makeBoolean);
predefined.put("object__makeBytes", this::object__makeBytes);
predefined.put("object__makeDictionary", this::object__makeDictionary);
predefined.put("object__makeNull", this::object__makeNull);
predefined.put("object__makeNumber", this::object__makeNumber);
predefined.put("object__makeString", this::object__makeString);
predefined.put("object__setProperty", this::object__setProperty);
predefined.put("object__subscript", this::object__subscript);
predefined.put("object__toString", this::object__toString);
predefined.put("print", this::print);
predefined.put("str", this::number__toString);
predefined.put("string__append", this::string__append);
predefined.put("string__concat", this::string__concat);
predefined.put("string__index", this::string__index);
predefined.put("string__length", this::string__length);
predefined.put("string__substring", this::string__substring);
predefined.put("string__toBytes", this::string__toBytes);
predefined.put("string__toString", this::string__toString);
predefined.put("math$abs", this::math$abs);
predefined.put("math$ceil", this::math$ceil);
predefined.put("math$floor", this::math$floor);
predefined.put("math$odd", this::math$odd);
predefined.put("math$sign", this::math$sign);
predefined.put("math$trunc", this::math$trunc);
predefined.put("random$uint32", this::random$uint32);
predefined.put("runtime$assertionsEnabled", this::runtime$assertionsEnabled);
predefined.put("runtime$createObject", this::runtime$createObject);
predefined.put("runtime$executorName", this::runtime$executorName);
predefined.put("string$fromCodePoint", this::string$fromCodePoint);
predefined.put("string$toCodePoint", this::string$toCodePoint);
predefined.put("sys$exit", this::sys$exit);
predefined.put("textio$close", this::textio$close);
predefined.put("textio$open", this::textio$open);
predefined.put("textio$readLine", this::textio$readLine);
predefined.put("textio$writeLine", this::textio$writeLine);
this.args = new ArrayList<Cell>();
for (String x: args) {
this.args.add(new Cell(x));
}
object = new Bytecode(in);
ip = 0;
callstack = new ArrayDeque<Integer>();
stack = new ArrayDeque<Cell>();
globals = new Cell[object.global_size];
for (int i = 0; i < object.global_size; i++) {
globals[i] = new Cell();
}
frames = new ArrayDeque<ActivationFrame>();
}
void run()
{
ip = object.code.size();
invoke(0);
execLoop(0);
}
void execLoop(int min_callstack_depth)
{
while (callstack.size() > min_callstack_depth && ip < object.code.size()) {
//System.err.println("ip=" + ip + " op=" + opcodes[object.code.get(ip)]);
//for (Cell c: stack) { System.err.println(" " + c); }
try {
switch (opcodes[object.code.get(ip)]) {
case PUSHB: doPUSHB(); break;
case PUSHN: doPUSHN(); break;
case PUSHS: doPUSHS(); break;
case PUSHY: doPUSHY(); break;
case PUSHPG: doPUSHPG(); break;
case PUSHPPG: doPUSHPPG(); break;
//case PUSHPMG
case PUSHPL: doPUSHPL(); break;
case PUSHPOL: doPUSHPOL(); break;
case PUSHI: doPUSHI(); break;
case LOADB: doLOADB(); break;
case LOADN: doLOADN(); break;
case LOADS: doLOADS(); break;
case LOADY: doLOADY(); break;
case LOADA: doLOADA(); break;
case LOADD: doLOADD(); break;
case LOADP: doLOADP(); break;
case LOADJ: doLOADJ(); break;
//case LOADV
case STOREB: doSTOREB(); break;
case STOREN: doSTOREN(); break;
case STORES: doSTORES(); break;
case STOREY: doSTOREY(); break;
case STOREA: doSTOREA(); break;
case STORED: doSTORED(); break;
case STOREP: doSTOREP(); break;
case STOREJ: doSTOREJ(); break;
//case STOREV
case NEGN: doNEGN(); break;
case ADDN: doADDN(); break;
case SUBN: doSUBN(); break;
case MULN: doMULN(); break;
case DIVN: doDIVN(); break;
case MODN: doMODN(); break;
case EXPN: doEXPN(); break;
case EQB: doEQB(); break;
case NEB: doNEB(); break;
case EQN: doEQN(); break;
case NEN: doNEN(); break;
case LTN: doLTN(); break;
case GTN: doGTN(); break;
case LEN: doLEN(); break;
case GEN: doGEN(); break;
case EQS: doEQS(); break;
case NES: doNES(); break;
case LTS: doLTS(); break;
case GTS: doGTS(); break;
case LES: doLES(); break;
case GES: doGES(); break;
case EQY: doEQY(); break;
case NEY: doNEY(); break;
case LTY: doLTY(); break;
//case GTY
//case LEY
//case GEY
case EQA: doEQA(); break;
case NEA: doNEA(); break;
//case EQD
//case NED
case EQP: doEQP(); break;
case NEP: doNEP(); break;
//case EQV
//case NEV
//case ANDB
//case ORB
case NOTB: doNOTB(); break;
case INDEXAR: doINDEXAR(); break;
case INDEXAW: doINDEXAW(); break;
case INDEXAV: doINDEXAV(); break;
case INDEXAN: doINDEXAN(); break;
case INDEXDR: doINDEXDR(); break;
case INDEXDW: doINDEXDW(); break;
case INDEXDV: doINDEXDV(); break;
case INA: doINA(); break;
case IND: doIND(); break;
case CALLP: doCALLP(); break;
case CALLF: doCALLF(); break;
//case CALLMF
//case CALLI
case JUMP: doJUMP(); break;
case JF: doJF(); break;
case JT: doJT(); break;
case DUP: doDUP(); break;
case DUPX1: doDUPX1(); break;
case DROP: doDROP(); break;
case RET: doRET(); break;
case CONSA: doCONSA(); break;
case CONSD: doCONSD(); break;
case EXCEPT: doEXCEPT(); break;
case ALLOC: doALLOC(); break;
case PUSHNIL: doPUSHNIL(); break;
case RESETC: doRESETC(); break;
//case PUSHPEG
case JUMPTBL: doJUMPTBL(); break;
//case CALLX
case SWAP: doSWAP(); break;
//case DROPN
//case PUSHFP
case CALLV: doCALLV(); break;
case PUSHCI: doPUSHCI(); break;
default:
System.err.println("Unknown opcode: " + opcodes[object.code.get(ip)]);
System.exit(1);
}
} catch (NeonException x) {
raiseLiteral(x.name, x.info);
}
}
}
public static void main(String[] args)
{
try {
new Executor(new DataInputStream(new FileInputStream(args[0])), args).run();
} catch (java.io.FileNotFoundException x) {
System.err.println(x);
System.exit(1);
}
}
private int getVint()
{
int r = 0;
while (true) {
byte x = object.code.get(ip);
ip++;
if ((r & 0xff000000) != 0) {
System.err.println("Integer value exceeds maximum");
System.exit(1);
}
r = (r << 7) | (x & 0x7f);
if ((x & 0x80) == 0) {
break;
}
}
return r;
}
private void doPUSHB()
{
ip++;
boolean val = object.code.get(ip++) != 0;
stack.addFirst(new Cell(val));
}
private void doPUSHN()
{
ip++;
int val = getVint();
stack.addFirst(new Cell(new BigDecimal(object.strtable[val])));
}
private void doPUSHS()
{
ip++;
int val = getVint();
stack.addFirst(new Cell(object.strtable[val]));
}
private void doPUSHY()
{
ip++;
int val = getVint();
stack.addFirst(new Cell(object.bytetable[val]));
}
private void doPUSHPG()
{
ip++;
int addr = getVint();
stack.addFirst(new Cell(globals[addr]));
}
private void doPUSHPPG()
{
ip++;
int val = getVint();
String s = object.strtable[val];
switch (s) {
case "sys$args":
stack.addFirst(new Cell(new Cell(args)));
break;
case "textio$stderr":
stack.addFirst(new Cell(new Cell(new NeObjectNative(System.err))));
break;
case "textio$stdout":
stack.addFirst(new Cell(new Cell(new NeObjectNative(System.out))));
break;
default:
assert false : s;
}
}
private void doPUSHPL()
{
ip++;
int addr = getVint();
stack.addFirst(new Cell(frames.getFirst().locals[addr]));
}
private void doPUSHPOL()
{
ip++;
int back = getVint();
int addr = getVint();
ActivationFrame frame = frames.getFirst();
while (back > 0) {
frame = frame.outer;
back
}
stack.addFirst(new Cell(frame.locals[addr]));
}
private void doPUSHI()
{
ip++;
int x = getVint();
stack.addFirst(new Cell(BigDecimal.valueOf(x)));
}
private void doLOADB()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getBoolean()));
}
private void doLOADN()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getNumber()));
}
private void doLOADS()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getString()));
}
private void doLOADY()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getBytes()));
}
private void doLOADA()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getArray()));
}
private void doLOADD()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getDictionary()));
}
private void doLOADP()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getAddress()));
}
private void doLOADJ()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
stack.addFirst(new Cell(addr.getObject()));
}
private void doSTOREB()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
boolean val = stack.removeFirst().getBoolean();
addr.set(val);
}
private void doSTOREN()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
BigDecimal val = stack.removeFirst().getNumber();
addr.set(val);
}
private void doSTORES()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
String val = stack.removeFirst().getString();
addr.set(val);
}
private void doSTOREY()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
byte[] val = stack.removeFirst().getBytes();
addr.set(val);
}
private void doSTOREA()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
List<Cell> val = stack.removeFirst().getArray();
addr.set(val);
}
private void doSTORED()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
Map<String, Cell> val = stack.removeFirst().getDictionary();
addr.set(val);
}
private void doSTOREP()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
Cell val = stack.removeFirst().getAddress();
addr.set(val);
}
private void doSTOREJ()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
NeObject val = stack.removeFirst().getObject();
addr.set(val);
}
private void doNEGN()
{
ip++;
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.negate()));
}
private void doADDN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.add(b)));
}
private void doSUBN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.subtract(b)));
}
private void doMULN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.multiply(b)));
}
private void doDIVN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
if (b.signum() == 0) {
raiseLiteral("DivideByZeroException");
return;
}
stack.addFirst(new Cell(a.divide(b)));
}
private void doMODN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.remainder(b)));
}
private void doEXPN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
try {
int p = b.intValue();
if (p >= 0) {
BigDecimal r = BigDecimal.ONE;
while (p != 0) {
if ((p & 1) != 0) {
r = r.multiply(a);
}
a = a.multiply(a);
p >>= 1;
}
stack.addFirst(new Cell(r));
return;
}
} catch (ArithmeticException x) {
}
stack.addFirst(new Cell(BigDecimalMath.pow(a, b)));
}
private void doEQB()
{
ip++;
boolean b = stack.removeFirst().getBoolean();
boolean a = stack.removeFirst().getBoolean();
stack.addFirst(new Cell(a == b));
}
private void doNEB()
{
ip++;
boolean b = stack.removeFirst().getBoolean();
boolean a = stack.removeFirst().getBoolean();
stack.addFirst(new Cell(a != b));
}
private void doEQN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) == 0));
}
private void doNEN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) != 0));
}
private void doLTN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) < 0));
}
private void doGTN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) > 0));
}
private void doLEN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) <= 0));
}
private void doGEN()
{
ip++;
BigDecimal b = stack.removeFirst().getNumber();
BigDecimal a = stack.removeFirst().getNumber();
stack.addFirst(new Cell(a.compareTo(b) >= 0));
}
private void doEQS()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a.equals(b)));
}
private void doNES()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(!a.equals(b)));
}
private void doLTS()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a.compareTo(b) < 0));
}
private void doGTS()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a.compareTo(b) > 0));
}
private void doLES()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a.compareTo(b) <= 0));
}
private void doGES()
{
ip++;
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a.compareTo(b) >= 0));
}
private void doEQY()
{
ip++;
byte[] b = stack.removeFirst().getBytes();
byte[] a = stack.removeFirst().getBytes();
stack.addFirst(new Cell(a.equals(b)));
}
private void doNEY()
{
ip++;
byte[] b = stack.removeFirst().getBytes();
byte[] a = stack.removeFirst().getBytes();
stack.addFirst(new Cell(!a.equals(b)));
}
private void doLTY()
{
ip++;
byte[] b = stack.removeFirst().getBytes();
byte[] a = stack.removeFirst().getBytes();
boolean r = a.length < b.length;
for (int i = 0; i < a.length; i++) {
if (i >= b.length) {
break;
}
if (a[i] < b[i]) {
r = true;
break;
} else if (a[i] > b[i]) {
r = false;
break;
}
}
stack.addFirst(new Cell(r));
}
private void doEQA()
{
ip++;
Cell b = stack.removeFirst();
Cell a = stack.removeFirst();
stack.addFirst(new Cell(a.equals(b)));
}
private void doNEA()
{
ip++;
Cell b = stack.removeFirst();
Cell a = stack.removeFirst();
stack.addFirst(new Cell(!a.equals(b)));
}
private void doEQP()
{
ip++;
Cell b = stack.removeFirst().getAddress();
Cell a = stack.removeFirst().getAddress();
stack.addFirst(new Cell(a == b));
}
private void doNEP()
{
ip++;
Cell b = stack.removeFirst().getAddress();
Cell a = stack.removeFirst().getAddress();
stack.addFirst(new Cell(a != b));
}
private void doNOTB()
{
ip++;
boolean x = stack.removeFirst().getBoolean();
stack.addFirst(new Cell(!x));
}
private void doINDEXAR()
{
ip++;
BigDecimal index = stack.removeFirst().getNumber();
List<Cell> array = stack.removeFirst().getAddress().getArray();
try {
index.intValueExact();
} catch (ArithmeticException x) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
if (index.signum() < 0 || index.intValue() >= array.size()) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
stack.addFirst(new Cell(array.get(index.intValue())));
}
private void doINDEXAW()
{
ip++;
BigDecimal index = stack.removeFirst().getNumber();
List<Cell> array = stack.removeFirst().getAddress().getArray();
try {
index.intValueExact();
} catch (ArithmeticException x) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
if (index.signum() < 0) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
int i = index.intValue();
while (i >= array.size()) {
array.add(new Cell());
}
stack.addFirst(new Cell(array.get(i)));
}
private void doINDEXAV()
{
ip++;
BigDecimal index = stack.removeFirst().getNumber();
List<Cell> array = stack.removeFirst().getArray();
try {
index.intValueExact();
} catch (ArithmeticException x) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
if (index.signum() < 0 || index.intValue() >= array.size()) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
stack.addFirst(array.get(index.intValue()));
}
private void doINDEXAN()
{
ip++;
BigDecimal index = stack.removeFirst().getNumber();
List<Cell> array = stack.removeFirst().getArray();
try {
index.intValueExact();
} catch (ArithmeticException x) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
if (index.signum() < 0) {
raiseLiteral("ArrayIndexException", index.toString());
return;
}
int i = index.intValue();
if (i < array.size()) {
stack.addFirst(array.get(i));
} else {
stack.addFirst(new Cell());
}
}
private void doINDEXDR()
{
ip++;
String key = stack.removeFirst().getString();
Map<String, Cell> dictionary = stack.removeFirst().getAddress().getDictionary();
Cell r = dictionary.get(key);
if (r == null) {
raiseLiteral("DictionaryIndexException", key);
return;
}
stack.addFirst(new Cell(r));
}
private void doINDEXDW()
{
ip++;
String key = stack.removeFirst().getString();
Map<String, Cell> dictionary = stack.removeFirst().getAddress().getDictionary();
Cell r = dictionary.get(key);
if (r == null) {
r = new Cell();
dictionary.put(key, r);
}
stack.addFirst(new Cell(r));
}
private void doINDEXDV()
{
ip++;
String key = stack.removeFirst().getString();
Map<String, Cell> dictionary = stack.removeFirst().getDictionary();
Cell r = dictionary.get(key);
if (r == null) {
raiseLiteral("DictionaryIndexException", key);
return;
}
stack.addFirst(r);
}
private void doINA()
{
ip++;
List<Cell> array = stack.removeFirst().getArray();
Cell val = stack.removeFirst();
for (Cell x: array) {
if (x.equals(val)) {
stack.addFirst(new Cell(true));
return;
}
}
stack.addFirst(new Cell(false));
}
private void doIND()
{
ip++;
Map<String, Cell> dict = stack.removeFirst().getDictionary();
String val = stack.removeFirst().getString();
stack.addFirst(new Cell(dict.containsKey(val)));
}
private void doCALLP()
{
ip++;
int func = getVint();
GenericFunction f = predefined.get(object.strtable[func]);
if (f != null) {
f.call();
} else {
System.err.println("Unknown function: " + object.strtable[func]);
System.exit(1);
}
}
private void doCALLF()
{
ip++;
int target = getVint();
invoke(target);
}
private void doJUMP()
{
ip++;
int target = getVint();
ip = target;
}
private void doJF()
{
ip++;
int target = getVint();
boolean a = stack.removeFirst().getBoolean();
if (!a) {
ip = target;
}
}
private void doJT()
{
ip++;
int target = getVint();
boolean a = stack.removeFirst().getBoolean();
if (a) {
ip = target;
}
}
private void doDUP()
{
ip++;
stack.addFirst(stack.getFirst().copy());
}
private void doDUPX1()
{
ip++;
Cell a = stack.removeFirst();
Cell b = stack.removeFirst();
stack.addFirst(a.copy());
stack.addFirst(b.copy());
stack.addFirst(a.copy());
}
private void doDROP()
{
ip++;
stack.removeFirst();
}
private void doRET()
{
frames.removeFirst();
ip = callstack.removeFirst();
}
private void doCONSA()
{
ip++;
int val = getVint();
List<Cell> a = new ArrayList<Cell>();
while (val > 0) {
a.add(stack.removeFirst());
val
}
stack.addFirst(new Cell(a));
}
private void doCONSD()
{
ip++;
int val = getVint();
Map<String, Cell> d = new TreeMap<String, Cell>();
while (val > 0) {
Cell value = stack.removeFirst();
String key = stack.removeFirst().getString();
d.put(key, value);
val
}
stack.addFirst(new Cell(d));
}
private void doEXCEPT()
{
int start_ip = ip;
ip++;
int val = getVint();
ip = start_ip;
NeObject info = stack.removeFirst().getObject();
raiseLiteral(object.strtable[val], info);
}
private void doALLOC()
{
ip++;
int val = getVint();
stack.addFirst(new Cell(new Cell(new ArrayList<Cell>(val))));
}
private void doPUSHNIL()
{
ip++;
stack.addFirst(new Cell((Cell)null));
}
private void doRESETC()
{
ip++;
Cell addr = stack.removeFirst().getAddress();
addr.reset();
}
private void doJUMPTBL()
{
ip++;
int val = getVint();
BigDecimal n = stack.removeFirst().getNumber();
try {
int i = n.intValueExact();
if (i >= 0 && i < val) {
ip += 6 * i;
} else {
ip += 6 * val;
}
} catch (ArithmeticException x) {
ip += 6 * val;
}
}
private void doSWAP()
{
ip++;
Cell a = stack.removeFirst();
Cell b = stack.removeFirst();
stack.addFirst(a);
stack.addFirst(b);
}
private void doCALLV()
{
ip++;
int val = getVint();
List<Cell> pi = stack.removeFirst().getArray();
Cell instance = pi.get(0).getAddress();
int interface_index = pi.get(1).getNumber().intValueExact();
//Module *m = reinterpret_cast<Module *>(instance->array_for_write()[0].array_for_write()[0].other());
Bytecode.ClassInfo classinfo = (Bytecode.ClassInfo)instance.getArray().get(0).getGeneric()[1];
invoke(classinfo.interfaces[interface_index][val]);
}
private void doPUSHCI()
{
ip++;
int val = getVint();
String name = object.strtable[val];
if (!name.contains(".")) {
for (Bytecode.ClassInfo c: object.classes) {
if (c.name == val) {
Cell ci = new Cell(new Object[] {null, c});
stack.addFirst(ci);
return;
}
}
} else {
// TODO
}
System.err.println("neon: unknown class name " + name);
System.exit(1);
}
private void invoke(int index)
{
callstack.addFirst(ip);
ActivationFrame outer = null;
int nest = object.functions[index].nest;
int params = object.functions[index].params;
int locals = object.functions[index].locals;
if (frames.size() > 0) {
assert nest <= frames.getFirst().nesting_depth+1;
outer = frames.getFirst();
while (outer != null && nest <= outer.nesting_depth) {
assert outer.outer == null || outer.nesting_depth == outer.outer.nesting_depth+1;
outer = outer.outer;
}
}
ActivationFrame frame = new ActivationFrame(nest, outer, locals, stack.size() - params);
frames.addFirst(frame);
ip = object.functions[index].entry;
}
private void raiseLiteral(String name)
{
raiseLiteral(name, "");
}
private void raiseLiteral(String name, String info)
{
raiseLiteral(name, new NeObjectString(info));
}
private void raiseLiteral(String name, NeObject info)
{
Cell exceptionvar = new Cell(new ArrayList<Cell>(Arrays.asList(
new Cell(name),
new Cell(info),
new Cell(BigDecimal.valueOf(ip))
)));
int tip = ip;
Iterator<Integer> si = callstack.iterator();
int depth = 0;
for (;;) {
for (Bytecode.ExceptionInfo e: object.exceptions) {
if (tip >= e.start && tip < e.end) {
String handler = object.strtable[e.excid];
if (name.equals(handler) || (name.length() > handler.length() && name.startsWith(handler) && name.charAt(handler.length()) == '.')) {
ip = e.handler;
while (depth > 0) {
callstack.removeFirst();
depth
}
stack.addFirst(exceptionvar);
return;
}
}
}
if (!si.hasNext()) {
break;
}
depth++;
tip = si.next();
}
System.err.println("Unhandled exception " + name + " (" + info + ")");
System.exit(1);
}
public static final int OPCODE_VERSION = 3;
public enum Opcode {
PUSHB,
PUSHN,
PUSHS,
PUSHY,
PUSHPG,
PUSHPPG,
PUSHPMG,
PUSHPL,
PUSHPOL,
PUSHI,
LOADB,
LOADN,
LOADS,
LOADY,
LOADA,
LOADD,
LOADP,
LOADJ,
LOADV,
STOREB,
STOREN,
STORES,
STOREY,
STOREA,
STORED,
STOREP,
STOREJ,
STOREV,
NEGN,
ADDN,
SUBN,
MULN,
DIVN,
MODN,
EXPN,
EQB,
NEB,
EQN,
NEN,
LTN,
GTN,
LEN,
GEN,
EQS,
NES,
LTS,
GTS,
LES,
GES,
EQY,
NEY,
LTY,
GTY,
LEY,
GEY,
EQA,
NEA,
EQD,
NED,
EQP,
NEP,
EQV,
NEV,
ANDB,
ORB,
NOTB,
INDEXAR,
INDEXAW,
INDEXAV,
INDEXAN,
INDEXDR,
INDEXDW,
INDEXDV,
INA,
IND,
CALLP,
CALLF,
CALLMF,
CALLI,
JUMP,
JF,
JT,
DUP,
DUPX1,
DROP,
RET,
CONSA,
CONSD,
EXCEPT,
ALLOC,
PUSHNIL,
RESETC,
PUSHPEG,
JUMPTBL,
CALLX,
SWAP,
DROPN,
PUSHFP,
CALLV,
PUSHCI,
}
private interface GenericFunction {
void call();
}
private Opcode[] opcodes = Opcode.values();
private Map<String, GenericFunction> predefined;
private List<Cell> args;
private Bytecode object;
private int ip;
private ArrayDeque<Integer> callstack;
private ArrayDeque<Cell> stack;
private Cell[] globals;
private ArrayDeque<ActivationFrame> frames;
java.util.Random gen = new java.util.Random();
private void array__append()
{
Cell v = stack.removeFirst();
List<Cell> a = stack.removeFirst().getAddress().getArray();
a.add(v);
}
private void array__concat()
{
List<Cell> b = stack.removeFirst().getArray();
List<Cell> a = stack.removeFirst().getArray();
List<Cell> r = new ArrayList<Cell>();
r.addAll(a);
r.addAll(b);
stack.addFirst(new Cell(r));
}
private void array__extend()
{
List<Cell> v = stack.removeFirst().getArray();
List<Cell> a = stack.removeFirst().getAddress().getArray();
a.addAll(v);
}
private void array__find()
{
Cell e = stack.removeFirst();
List<Cell> a = stack.removeFirst().getArray();
for (int i = 0; i < a.size(); i++) {
if (a.get(i).equals(e)) {
stack.addFirst(new Cell(BigDecimal.valueOf(i)));
return;
}
}
raiseLiteral("ArrayIndexException", "value not found in array");
}
private void array__remove()
{
int index = stack.removeFirst().getNumber().intValueExact();
List<Cell> a = stack.removeFirst().getAddress().getArray();
a.remove(index);
}
private void array__reversed()
{
List<Cell> a = stack.removeFirst().getArray();
List<Cell> r = new ArrayList<Cell>();
for (int i = 0; i < a.size(); i++) {
r.add(a.get(i).copy());
}
java.util.Collections.reverse(r);
stack.addFirst(new Cell(r));
}
private void array__size()
{
List<Cell> a = stack.removeFirst().getArray();
stack.addFirst(new Cell(BigDecimal.valueOf(a.size())));
}
private void array__slice()
{
boolean last_from_end = stack.removeFirst().getBoolean();
BigDecimal nlast = stack.removeFirst().getNumber();
boolean first_from_end = stack.removeFirst().getBoolean();
BigDecimal nfirst = stack.removeFirst().getNumber();
List<Cell> a = stack.removeFirst().getArray();
if (nfirst.stripTrailingZeros().scale() > 0) {
raiseLiteral("ArrayIndexException", nfirst.toString());
return;
}
if (nlast.stripTrailingZeros().scale() > 0) {
raiseLiteral("ArrayIndexException", nlast.toString());
return;
}
int first = nfirst.intValue();
int last = nlast.intValue();
if (first_from_end) {
first += a.size() - 1;
}
if (first < 0) {
first = 0;
}
if (first > a.size()) {
first = a.size();
}
if (last_from_end) {
last += a.size() - 1;
}
if (last >= a.size()) {
last = a.size() - 1;
}
if (last < first) {
last = first - 1;
}
stack.addFirst(new Cell(a.subList(first, last+1)));
}
private void array__splice()
{
boolean last_from_end = stack.removeFirst().getBoolean();
int last = stack.removeFirst().getNumber().intValueExact();
boolean first_from_end = stack.removeFirst().getBoolean();
int first = stack.removeFirst().getNumber().intValueExact();
List<Cell> a = stack.removeFirst().getArray();
List<Cell> b = stack.removeFirst().getArray();
if (first_from_end) {
first += a.size() - 1;
}
if (last_from_end) {
last += a.size() - 1;
}
List<Cell> r = new ArrayList<Cell>();
r.addAll(a.subList(0, first));
r.addAll(b);
r.addAll(a.subList(last+1, a.size()));
stack.addFirst(new Cell(r));
}
private void array__toBytes__number()
{
List<Cell> a = stack.removeFirst().getArray();
byte[] r = new byte[a.size()];
int i = 0;
for (Cell c: a) {
r[i] = (byte) c.getNumber().intValue();
i++;
}
stack.addFirst(new Cell(r));
}
private void array__toString__number()
{
List<Cell> a = stack.removeFirst().getArray();
StringBuilder r = new StringBuilder("[");
boolean first = true;
for (Cell x: a) {
if (first) {
first = false;
} else {
r.append(", ");
}
r.append(x.getNumber());
}
r.append("]");
stack.addFirst(new Cell(r.toString()));
}
private void array__toString__string()
{
List<Cell> a = stack.removeFirst().getArray();
StringBuilder r = new StringBuilder("[");
boolean first = true;
for (Cell x: a) {
if (first) {
first = false;
} else {
r.append(", ");
}
r.append('"' + x.getString() + '"');
}
r.append("]");
stack.addFirst(new Cell(r.toString()));
}
private void array__toString__object()
{
List<Cell> a = stack.removeFirst().getArray();
StringBuilder r = new StringBuilder("[");
boolean first = true;
for (Cell x: a) {
if (first) {
first = false;
} else {
r.append(", ");
}
r.append(x.getObject().toString());
}
r.append("]");
stack.addFirst(new Cell(r.toString()));
}
private void boolean__toString()
{
boolean b = stack.removeFirst().getBoolean();
stack.addFirst(new Cell(b ? "TRUE" : "FALSE"));
}
private void bytes__decodeToString()
{
byte[] b = stack.removeFirst().getBytes();
stack.addFirst(new Cell(new String(b)));
}
private void bytes__index()
{
int index = stack.removeFirst().getNumber().intValueExact();
byte[] b = stack.removeFirst().getBytes();
stack.addFirst(new Cell(BigDecimal.valueOf(b[index])));
}
private void bytes__range()
{
boolean last_from_end = stack.removeFirst().getBoolean();
int last = stack.removeFirst().getNumber().intValueExact();
boolean first_from_end = stack.removeFirst().getBoolean();
int first = stack.removeFirst().getNumber().intValueExact();
byte[] b = stack.removeFirst().getBytes();
if (first_from_end) {
first += b.length - 1;
}
if (last_from_end) {
last += b.length - 1;
}
stack.addFirst(new Cell(Arrays.copyOfRange(b, first, last+1)));
}
private void bytes__size()
{
byte[] b = stack.removeFirst().getBytes();
stack.addFirst(new Cell(BigDecimal.valueOf(b.length)));
}
private void bytes__splice()
{
boolean last_from_end = stack.removeFirst().getBoolean();
int last = stack.removeFirst().getNumber().intValueExact();
boolean first_from_end = stack.removeFirst().getBoolean();
int first = stack.removeFirst().getNumber().intValueExact();
byte[] a = stack.removeFirst().getBytes();
byte[] b = stack.removeFirst().getBytes();
if (first_from_end) {
first += a.length - 1;
}
if (last_from_end) {
last += a.length - 1;
}
byte[] r = new byte[first + b.length + a.length-(last+1)];
System.arraycopy(a, 0, r, 0, first);
System.arraycopy(b, 0, r, first, b.length);
System.arraycopy(a, last+1, r, first+b.length, a.length-(last+1));
stack.addFirst(new Cell(r));
}
private void bytes__toArray()
{
byte[] b = stack.removeFirst().getBytes();
List<Cell> a = new ArrayList<Cell>();
for (byte x: b) {
a.add(new Cell(BigDecimal.valueOf(x & 0xff)));
}
stack.addFirst(new Cell(a));
}
private void bytes__toString()
{
byte[] b = stack.removeFirst().getBytes();
StringBuilder r = new StringBuilder("HEXBYTES \"");
boolean first = true;
for (byte c: b) {
if (!first) {
r.append(' ');
} else {
first = false;
}
r.append(String.format("%02x", c & 0xff));
}
r.append("\"");
stack.addFirst(new Cell(r.toString()));
}
private void dictionary__keys()
{
Map<String, Cell> d = stack.removeFirst().getDictionary();
List<Cell> r = new ArrayList<Cell>();
for (String k: d.keySet()) {
r.add(new Cell(k));
}
stack.addFirst(new Cell(r));
}
private void dictionary__remove()
{
String key = stack.removeFirst().getString();
Map<String, Cell> d = stack.removeFirst().getAddress().getDictionary();
d.remove(key);
}
private void exceptiontype__toString()
{
List<Cell> a = stack.removeFirst().getArray();
stack.addFirst(new Cell("<ExceptionType:" + a.get(0).getString() + "," + a.get(1).getObject().toString() + "," + a.get(2).getNumber() + ">"));
}
private void num()
{
String s = stack.removeFirst().getString();
boolean any_digits = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
any_digits = true;
break;
}
}
if (any_digits) {
try {
stack.addFirst(new Cell(new BigDecimal(s)));
} catch (NumberFormatException x) {
raiseLiteral("ValueRangeException");
}
} else {
raiseLiteral("ValueRangeException");
}
}
private void number__toString()
{
BigDecimal n = stack.removeFirst().getNumber();
String s = n.toString();
if (s.indexOf('.') >= 0) {
while (s.length() > 1 && s.charAt(s.length()-1) == '0') {
s = s.substring(0, s.length()-1);
}
if (s.charAt(s.length()-1) == '.') {
s = s.substring(0, s.length()-1);
}
}
stack.addFirst(new Cell(s));
}
private void object__getArray()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
List<NeObject> a = o.getArray();
if (a == null) {
raiseLiteral("DynamicConversionException");
return;
}
List<Cell> r = new ArrayList<Cell>();
for (NeObject x: a) {
r.add(new Cell(x));
}
stack.addFirst(new Cell(r));
}
private void object__getBoolean()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
Boolean b = o.getBoolean();
if (b == null) {
raiseLiteral("DynamicConversionException");
return;
}
stack.addFirst(new Cell(b));
}
private void object__getBytes()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
byte[] b = o.getBytes();
if (b == null) {
raiseLiteral("DynamicConversionException");
return;
}
stack.addFirst(new Cell(b));
}
private void object__getDictionary()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
Map<String, NeObject> d = o.getDictionary();
if (d == null) {
raiseLiteral("DynamicConversionException");
return;
}
Map<String, Cell> r = new TreeMap<String, Cell>();
for (Map.Entry<String, NeObject> x: d.entrySet()) {
r.put(x.getKey(), new Cell(x.getValue()));
}
stack.addFirst(new Cell(r));
}
private void object__getNumber()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
BigDecimal n = o.getNumber();
if (n == null) {
raiseLiteral("DynamicConversionException");
return;
}
stack.addFirst(new Cell(n));
}
private void object__getString()
{
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException");
return;
}
String s = o.getString();
if (s == null) {
raiseLiteral("DynamicConversionException");
return;
}
stack.addFirst(new Cell(s));
}
private void object__invokeMethod()
{
List<Cell> a = stack.removeFirst().getArray();
String name = stack.removeFirst().getString();
List<NeObject> args = new ArrayList<NeObject>();
for (Cell x: a) {
args.add(x.getObject());
}
NeObject r = stack.removeFirst().getObject().invokeMethod(name, args);
stack.addFirst(new Cell(r));
}
private void object__isNull()
{
NeObject o = stack.removeFirst().getObject();
stack.addFirst(new Cell(o == null));
}
private void object__makeArray()
{
List<Cell> a = stack.removeFirst().getArray();
List<NeObject> r = new ArrayList<NeObject>();
for (Cell x: a) {
r.add(x.getObject());
}
stack.addFirst(new Cell(new NeObjectArray(r)));
}
private void object__makeBoolean()
{
boolean b = stack.removeFirst().getBoolean();
stack.addFirst(new Cell(new NeObjectBoolean(b)));
}
private void object__makeBytes()
{
byte[] b = stack.removeFirst().getBytes();
stack.addFirst(new Cell(new NeObjectBytes(b)));
}
private void object__makeDictionary()
{
Map<String, Cell> d = stack.removeFirst().getDictionary();
Map<String, NeObject> r = new TreeMap<String, NeObject>();
for (Map.Entry<String, Cell> x: d.entrySet()) {
r.put(x.getKey(), x.getValue().getObject());
}
stack.addFirst(new Cell(new NeObjectDictionary(r)));
}
private void object__makeNull()
{
stack.addFirst(new Cell((NeObject)null));
}
private void object__makeNumber()
{
BigDecimal n = stack.removeFirst().getNumber();
stack.addFirst(new Cell(new NeObjectNumber(n)));
}
private void object__makeString()
{
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(new NeObjectString(s)));
}
private void object__setProperty()
{
NeObject i = stack.removeFirst().getObject();
NeObject o = stack.removeFirst().getObject();
NeObject v = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException", "object is null");
return;
}
if (i == null) {
raiseLiteral("DynamicConversionException", "index is null");
return;
}
o.setProperty(i, v);
}
private void object__subscript()
{
NeObject i = stack.removeFirst().getObject();
NeObject o = stack.removeFirst().getObject();
if (o == null) {
raiseLiteral("DynamicConversionException", "object is null");
return;
}
if (i == null) {
raiseLiteral("DynamicConversionException", "index is null");
return;
}
NeObject r = o.subscript(i);
if (r == null) {
raiseLiteral("ObjectSubscriptException", i.toString());
return;
}
stack.addFirst(new Cell(r));
}
private void object__toString()
{
NeObject o = stack.removeFirst().getObject();
stack.addFirst(new Cell(o != null ? o.toString() : "null"));
}
private void print()
{
System.out.println(stack.removeFirst().getString());
}
private void string__append()
{
String b = stack.removeFirst().getString();
Cell a = stack.removeFirst().getAddress();
a.set(a.getString() + b);
}
private void string__concat()
{
String b = stack.removeFirst().getString();
String a = stack.removeFirst().getString();
stack.addFirst(new Cell(a + b));
}
private void string__index()
{
int index = stack.removeFirst().getNumber().intValue();
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(s.substring(index, index+1)));
}
private void string__length()
{
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(BigDecimal.valueOf(s.length())));
}
private void string__substring()
{
boolean last_from_end = stack.removeFirst().getBoolean();
int last = stack.removeFirst().getNumber().intValue();
boolean first_from_end = stack.removeFirst().getBoolean();
int first = stack.removeFirst().getNumber().intValue();
String s = stack.removeFirst().getString();
if (first_from_end) {
first += s.length() - 1;
}
if (last_from_end) {
last += s.length() - 1;
}
stack.addFirst(new Cell(s.substring(first, last+1)));
}
private void string__toBytes()
{
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(s.getBytes()));
}
private void string__toString()
{
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(s));
}
private void math$abs()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.abs()));
}
private void math$ceil()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.divide(BigDecimal.ONE, BigDecimal.ROUND_CEILING)));
}
private void math$floor()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.divide(BigDecimal.ONE, BigDecimal.ROUND_FLOOR)));
}
private void math$odd()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.remainder(new BigDecimal(2)).compareTo(BigDecimal.ZERO) != 0));
}
private void math$sign()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(new BigDecimal(x.signum())));
}
private void math$trunc()
{
BigDecimal x = stack.removeFirst().getNumber();
stack.addFirst(new Cell(x.divide(BigDecimal.ONE, BigDecimal.ROUND_DOWN)));
}
private void random$uint32()
{
stack.addFirst(new Cell(BigDecimal.valueOf(gen.nextInt(0x10000000))));
}
private void runtime$assertionsEnabled()
{
stack.addFirst(new Cell(enable_assert));
}
private void runtime$createObject()
{
String name = stack.removeFirst().getString();
try {
Object obj = Class.forName(name).newInstance();
stack.addFirst(new Cell(new NeObjectNative(obj)));
} catch (ClassNotFoundException cnfe) {
stack.addFirst(new Cell(new NeObjectNative(null))); // TODO: exception
} catch (InstantiationException ie) {
stack.addFirst(new Cell(new NeObjectNative(null))); // TODO: exception
} catch (IllegalAccessException iae) {
stack.addFirst(new Cell(new NeObjectNative(null))); // TODO: exception
}
}
private void runtime$executorName()
{
stack.addFirst(new Cell("jnex"));
}
private void string$fromCodePoint()
{
BigDecimal n = stack.removeFirst().getNumber();
stack.addFirst(new Cell(new String(new int[] {n.intValue()}, 0, 1)));
}
private void string$toCodePoint()
{
String s = stack.removeFirst().getString();
stack.addFirst(new Cell(BigDecimal.valueOf(s.charAt(0))));
}
private void sys$exit()
{
BigDecimal n = stack.removeFirst().getNumber();
System.exit(n.intValue());
}
private void textio$close()
{
NeObject f = stack.removeFirst().getObject();
try {
((java.io.Closeable)f.getNative()).close();
} catch (java.io.IOException e) {
raiseLiteral("TextioException");
}
}
private void textio$open()
{
int mode = stack.removeFirst().getNumber().intValueExact();
String name = stack.removeFirst().getString();
try {
Object f;
switch (mode) {
case 0: // TODO: enum read
f = new java.io.BufferedReader(new java.io.FileReader(name));
break;
case 1: // TODO: enum write
f = new java.io.PrintStream(new java.io.FileOutputStream(name));
break;
default:
raiseLiteral("TextioException.Open", "open error");
return;
}
stack.addFirst(new Cell(new NeObjectNative(f)));
} catch (java.io.FileNotFoundException e) {
raiseLiteral("TextioException.Open", "open error");
}
}
private void textio$readLine()
{
NeObject f = stack.removeFirst().getObject();
try {
String s = ((java.io.BufferedReader)f.getNative()).readLine();
stack.addFirst(new Cell(true));
stack.addFirst(new Cell(s));
} catch (java.io.IOException e) {
raiseLiteral("TextioException");
}
}
private void textio$writeLine()
{
String s = stack.removeFirst().getString();
java.io.PrintStream f = (java.io.PrintStream)stack.removeFirst().getObject().getNative();
f.println(s);
}
}
|
package it.backbox.client.rest;
import it.backbox.IRestClient;
import it.backbox.bean.ProxyConfiguration;
import it.backbox.client.http.MultipartContent.MultipartFormDataContent;
import it.backbox.client.oauth.OAuth2Client;
import it.backbox.client.rest.bean.BoxError;
import it.backbox.client.rest.bean.BoxFile;
import it.backbox.client.rest.bean.BoxFolder;
import it.backbox.client.rest.bean.BoxItemCollection;
import it.backbox.client.rest.bean.BoxSearchResult;
import it.backbox.client.rest.bean.BoxUploadedFile;
import it.backbox.client.rest.bean.BoxUserInfo;
import it.backbox.exception.BackBoxException;
import it.backbox.exception.RestException;
import it.backbox.progress.ProgressManager;
import it.backbox.progress.stream.InputStreamCounter;
import it.backbox.progress.stream.OutputStreamCounter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.ExponentialBackOffPolicy;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.GenericData;
public class RestClient implements IRestClient {
private static final Logger _log = Logger.getLogger(RestClient.class.getCanonicalName());
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String baseUri = "https://api.box.com/2.0/";
private static final String baseUriUpload = "https://upload.box.com/api/2.0/files/";
private HttpRequestFactory requestFactory;
private Credential credential;
private class RestHttpRequestInitializer implements HttpRequestInitializer {
@Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
request.setParser(new JsonObjectParser(JSON_FACTORY));
// request.setReadTimeout(60*60*1000);
request.setBackOffPolicy(new CustomBackOffPolicy());
}
}
/**
* Constructor
*
* @throws Exception
*/
public RestClient() throws Exception {
this(null);
}
/**
* Constructor
*
* @param pc
* Proxy configuration
* @throws Exception
*/
public RestClient(ProxyConfiguration pc) throws Exception {
if ((pc == null) || !pc.isEnabled())
HTTP_TRANSPORT = new NetHttpTransport();
else {
String address = pc.getAddress();
int port = pc.getPort();
if ((address == null) || address.isEmpty() || (port <= 0))
throw new BackBoxException("Proxy configuration not valid");
HTTP_TRANSPORT = new NetHttpTransport.Builder().setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(address, port))).build();
}
credential = OAuth2Client.getCredential(HTTP_TRANSPORT);
requestFactory = HTTP_TRANSPORT.createRequestFactory(new RestHttpRequestInitializer());
if (_log.isLoggable(Level.INFO)) _log.info("Rest Client init ok");
}
/**
* Execute an HTTP request
*
* @param request
* Request to execute
* @return The HTTP response
* @throws IOException
* Parsing error failed
* @throws RestException
* HTTP Error
*/
private HttpResponse execute(HttpRequest request) throws IOException, RestException {
HttpResponse response = null;
try {
response = request.execute();
} catch (HttpResponseException e) {
if (_log.isLoggable(Level.INFO)) _log.info("HTTP response exception throwed");
String message = new StringBuilder(request.getRequestMethod()).append(' ').append(request.getUrl()).append(" -> ").append(e.getStatusCode()).toString();
JsonObjectParser parser = new JsonObjectParser(JSON_FACTORY);
BoxError error = null;
if (e.getContent() != null)
error = parser.parseAndClose(new StringReader(e.getContent()), BoxError.class);
throw new RestException(message, e, error);
}
return response;
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#download(java.lang.String)
*/
@Override
public byte[] download(String fileID) throws IOException, RestException {
GenericUrl url = new GenericUrl(new StringBuilder(baseUri).append("files/").append(fileID).append("/content").toString());
HttpRequest request = requestFactory.buildGetRequest(url);
if (_log.isLoggable(Level.FINE)) _log.fine("Download: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("Download: " + response.getStatusCode());
if (response.getStatusCode() == 202) {
String retry = response.getHeaders().getRetryAfter();
try {
Thread.sleep(Long.parseLong(retry));
} catch (NumberFormatException | InterruptedException e) {
_log.log(Level.SEVERE, "Error waiting to retry the download, retrying now!", e);
}
response = execute(request);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamCounter outputStream = new OutputStreamCounter(baos, ProgressManager.DOWNLOAD_ID);
response.download(outputStream);
return baos.toByteArray();
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#upload(java.lang.String, java.lang.String, byte[], java.lang.String, java.lang.String)
*/
@Override
public BoxFile upload(String name, String fileID, byte[] content, String folderID, String sha1) throws RestException, IOException {
StringBuilder uri = new StringBuilder(baseUriUpload);
if (fileID != null)
uri.append(fileID).append('/');
uri.append("content");
GenericUrl url = new GenericUrl(uri.toString());
MultipartFormDataContent mpc = new MultipartFormDataContent();
mpc.addPart(new MultipartFormDataContent.Part(null, name, new InputStreamContent("application/octet-stream", new InputStreamCounter(new ByteArrayInputStream(content), ProgressManager.UPLOAD_ID))));
mpc.addPart(new MultipartFormDataContent.Part("filename", null, ByteArrayContent.fromString("file", name)));
mpc.addPart(new MultipartFormDataContent.Part("parent_id", null, ByteArrayContent.fromString("string", folderID)));
HttpRequest request = requestFactory.buildPostRequest(url, mpc);
if ((sha1 != null) && !sha1.isEmpty()) {
HttpHeaders h = new HttpHeaders();
List<String> sha = new ArrayList<String>();
sha.add(sha1);
h.set("Content-MD5", sha);
request.setHeaders(h);
}
if (_log.isLoggable(Level.FINE)) _log.fine("Upload: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("Upload: " + response.getStatusCode());
BoxUploadedFile file = response.parseAs(BoxUploadedFile.class);
if ((file == null) || (file.entries == null) || file.entries.isEmpty() || (file.entries.get(0) == null))
throw new RestException("Upload error: uploaded file informations not retrieved");
return file.entries.get(0);
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#delete(java.lang.String, boolean)
*/
@Override
public void delete(String fileID, boolean isFolder) throws RestException, IOException {
GenericUrl url = new GenericUrl(new StringBuilder(baseUri).append(isFolder ? "folders/" : "files/").append(fileID).toString());
if (isFolder)
url.put("recursive", "true");
HttpRequest request = requestFactory.buildDeleteRequest(url);
if (_log.isLoggable(Level.FINE)) _log.fine("Delete: " + request.getUrl().toString());
try {
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("Delete: " + response.getStatusCode());
} catch (RestException re) {
if (re.getHttpException().getStatusCode() != 404)
throw re;
if (_log.isLoggable(Level.WARNING)) _log.warning(new StringBuilder("Delete file/folder with id ").append(fileID).append(" returned 404").toString());
}
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#search(java.lang.String)
*/
@Override
public BoxSearchResult search(String query) throws IOException, RestException {
GenericUrl url = new GenericUrl(baseUri + "search");
url.put("query", query);
HttpRequest request = requestFactory.buildGetRequest(url);
if (_log.isLoggable(Level.FINE)) _log.fine("Search: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("Search: " + response.getStatusCode());
return response.parseAs(BoxSearchResult.class);
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#mkdir(java.lang.String, java.lang.String)
*/
@Override
public BoxFolder mkdir(String name, String parentFolderID) throws IOException, RestException {
GenericUrl url = new GenericUrl(baseUri + "folders");
GenericData data = new GenericData();
data.put("name", name);
GenericData parentData = new GenericData();
if (parentFolderID == null)
parentData.put("id", "0");
else
parentData.put("id", parentFolderID);
data.put("parent", parentData);
HttpRequest request = requestFactory.buildPostRequest(url, new JsonHttpContent(JSON_FACTORY, data));
if (_log.isLoggable(Level.FINE)) _log.fine("MkDir: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("MkDir: " + response.getStatusCode());
return response.parseAs(BoxFolder.class);
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#getFolderItems(java.lang.String)
*/
@Override
public BoxItemCollection getFolderItems(String folderID) throws IOException, RestException {
GenericUrl url = new GenericUrl(new StringBuilder(baseUri).append("folders/").append(folderID).append("/items").toString());
url.put("limit", "1000");
url.put("fields", "name,id,sha1");
HttpRequest request = requestFactory.buildGetRequest(url);
if (_log.isLoggable(Level.FINE)) _log.fine("getFolderItems: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("getFolderItems: " + response.getStatusCode());
return response.parseAs(BoxItemCollection.class);
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#getUserInfo()
*/
@Override
public BoxUserInfo getUserInfo() throws IOException, RestException {
GenericUrl url = new GenericUrl(baseUri + "users/me");
HttpRequest request = requestFactory.buildGetRequest(url);
if (_log.isLoggable(Level.FINE)) _log.fine("getUserInfo: " + request.getUrl().toString());
HttpResponse response = execute(request);
if (_log.isLoggable(Level.FINE)) _log.fine("getUserInfo: " + response.getStatusCode());
return response.parseAs(BoxUserInfo.class);
}
/*
* (non-Javadoc)
* @see it.backbox.IRestClient#isAccessTokenValid()
*/
@Override
public boolean isAccessTokenValid() {
// check if token will expire in 5 minutes
if ((credential == null)
|| (credential.getAccessToken() == null)
|| ((credential.getExpiresInSeconds() != null) && (credential.getExpiresInSeconds() <= 300)))
return false;
return true;
}
/**
* Custom BackOff Policy to include the status 429 - TOO MANY REQUEST in the policy
*/
public class CustomBackOffPolicy extends ExponentialBackOffPolicy {
@Override
public boolean isBackOffRequired(int statusCode) {
return super.isBackOffRequired(statusCode) || (statusCode == 429);
}
}
}
|
// ChatMsg.java
// Implementation of the Class ChatMsg
// Generated by Enterprise Architect
// Modification history:
package imcode.external.chat;
import java.util.*;
public class ChatMsg
{
private String _senderStr;
private int _msgType;
private String _msgTypeStr;
private String _chatMsg;
private String _recieverStr;
private int _reciever;
private int _number;
private int _sender;
private String _dateTime;
// private Date date;
/**
*Default constructor
*/
public ChatMsg(String chatMsg, String recieverStr,int reciever, int msgType, String msgTypeStr, String senderStr,int sender, String dateTime)
{
_chatMsg = chatMsg;
_reciever = reciever;
_recieverStr = recieverStr;
_msgType = msgType;
_msgTypeStr = msgTypeStr;
_senderStr = senderStr;
_dateTime = dateTime;
_sender = sender;
}
public String toString()
{
return _senderStr+" "+ _msgTypeStr+" "+_recieverStr+" : "+_chatMsg;
}
protected void setIdNumber(int number)
{
_number = number;
}
public int getIdNumber()
{
return _number;
}
public String getDateTime()
{
return _dateTime;
}
public String getMessage()
{
return _chatMsg;
}
public int getMsgType()
{
return _msgType;
}
public int getReciever()
{
return _reciever;
}
public String getRecieverStr()
{
return _recieverStr;
}
public String getMsgTypeStr()
{
return _msgTypeStr;
}
public String getSenderStr()
{
return _senderStr;
}
public int getSender()
{
return _sender;
}
}
|
package org.hisp.dhis.dxf2.metadata.objectbundle.hooks;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.feedback.ErrorCode;
import org.hisp.dhis.feedback.ErrorReport;
import org.hisp.dhis.scheduling.Job;
import org.hisp.dhis.scheduling.JobConfiguration;
import org.hisp.dhis.scheduling.JobConfigurationService;
import org.hisp.dhis.scheduling.JobType;
import org.hisp.dhis.scheduling.SchedulingManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronSequenceGenerator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.hisp.dhis.scheduling.DefaultSchedulingManager.CONTINOUS_CRON;
import static org.hisp.dhis.scheduling.DefaultSchedulingManager.HOUR_CRON;
import static org.hisp.dhis.scheduling.JobStatus.DISABLED;
public class JobConfigurationObjectBundleHook
extends AbstractObjectBundleHook
{
private static final Log log = LogFactory.getLog( JobConfigurationObjectBundleHook.class );
private static final int SUCCESS = 1;
@Autowired
private JobConfigurationService jobConfigurationService;
private SchedulingManager schedulingManager;
public void setSchedulingManager( SchedulingManager schedulingManager )
{
this.schedulingManager = schedulingManager;
}
private List<ErrorReport> validateCronForJobType( JobConfiguration jobConfiguration )
{
List<ErrorReport> errorReports = new ArrayList<>();
// Make list of all jobs for each job type
Map<JobType, List<JobConfiguration>> jobConfigurationForJobTypes = new HashMap<>();
jobConfigurationService.getAllJobConfigurations().stream()
.filter( configuration -> !Objects.equals( configuration.getUid(), jobConfiguration.getUid() ) )
.forEach( configuration -> {
List<JobConfiguration> jobConfigurationList = new ArrayList<>();
List<JobConfiguration> oldList = jobConfigurationForJobTypes.get( configuration.getJobType() );
if ( oldList != null )
{
jobConfigurationList.addAll( oldList );
}
jobConfigurationList.add( configuration );
jobConfigurationForJobTypes.put( configuration.getJobType(), jobConfigurationList );
} );
/*
* Validate that there are no other jobs of the same job type which are scheduled with the same cron.
*
* Also check if the job is trying to run continuously while other jobs of the same type is running continuously - this should not be allowed
*/
List<JobConfiguration> listForJobType = jobConfigurationForJobTypes.get( jobConfiguration.getJobType() );
if ( listForJobType != null )
{
for ( JobConfiguration jobConfig : listForJobType )
{
if ( jobConfiguration.isContinuousExecution() )
{
if ( jobConfig.isContinuousExecution() )
{
errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7001 ) );
}
}
else
{
if ( jobConfig.getCronExpression().equals( jobConfiguration.getCronExpression() ) )
{
errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7000 ) );
}
}
}
}
return errorReports;
}
private List<ErrorReport> validateInternal( JobConfiguration jobConfiguration )
{
List<ErrorReport> errorReports = new ArrayList<>();
JobConfiguration persitedJobConfiguration = jobConfigurationService.getJobConfigurationByUid( jobConfiguration.getUid() );
if ( persitedJobConfiguration != null && !persitedJobConfiguration.isConfigurable() )
{
if ( !Objects.equals( persitedJobConfiguration.compareTo( jobConfiguration ), SUCCESS ) )
{
errorReports
.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7003, jobConfiguration.getJobType() ) );
}
else
{
persitedJobConfiguration.setCronExpression( jobConfiguration.getCronExpression() );
jobConfiguration = persitedJobConfiguration;
}
}
if ( !jobConfiguration.isContinuousExecution() )
{
if ( Objects.isNull( jobConfiguration.getCronExpression() ) )
{
errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7004 ) );
return errorReports;
}
// Validate the cron expression
if ( !CronSequenceGenerator.isValidExpression( jobConfiguration.getCronExpression() ) )
{
errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7005 ) );
return errorReports;
}
}
// Validate cron expression with relation to all other jobs
errorReports.addAll( validateCronForJobType( jobConfiguration ) );
// Validate parameters
ErrorReport parameterValidation =
jobConfiguration.getJobParameters() != null ? jobConfiguration.getJobParameters().validate() : null;
if ( !Objects.isNull( parameterValidation ) )
{
errorReports.add( parameterValidation );
}
Job job = schedulingManager.getJob( jobConfiguration.getJobType() );
ErrorReport jobValidation = job.validate();
if ( jobValidation != null )
{
errorReports.add( jobValidation );
}
return errorReports;
}
@Override
public <T extends IdentifiableObject> List<ErrorReport> validate( T object, ObjectBundle bundle )
{
if ( !JobConfiguration.class.isInstance( object ) )
{
return new ArrayList<>();
}
JobConfiguration jobConfiguration = (JobConfiguration) object;
List<ErrorReport> errorReports = new ArrayList<>( validateInternal( jobConfiguration ) );
if ( errorReports.size() == 0 )
{
jobConfiguration.setNextExecutionTime( null );
if ( jobConfiguration.isContinuousExecution() )
{
jobConfiguration.setCronExpression( CONTINOUS_CRON );
}
log.info( "Validation of '" + jobConfiguration.getName() + "' succeeded" );
}
else
{
log.info( "Validation of '" + jobConfiguration.getName() + "' failed." );
log.info( errorReports );
}
return errorReports;
}
private boolean setDefaultCronExpressionWhenDisablingContinuousExectution( JobConfiguration newObject, JobConfiguration persistedObject )
{
return ( !newObject.isContinuousExecution() && persistedObject.isContinuousExecution() ) && newObject.getCronExpression().equals( CONTINOUS_CRON );
}
@Override
public void preUpdate( IdentifiableObject object, IdentifiableObject persistedObject, ObjectBundle bundle )
{
if ( !JobConfiguration.class.isInstance( object ) )
{
return;
}
JobConfiguration newObject = (JobConfiguration) object;
JobConfiguration persObject = (JobConfiguration) persistedObject;
newObject.setLastExecuted( persObject.getLastExecuted() );
newObject.setLastExecutedStatus( persObject.getLastExecutedStatus() );
newObject.setLastRuntimeExecution( persObject.getLastRuntimeExecution() );
if ( setDefaultCronExpressionWhenDisablingContinuousExectution( newObject, persObject ) )
{
newObject.setCronExpression( HOUR_CRON );
}
schedulingManager.stopJob( (JobConfiguration) persistedObject );
}
@Override
public <T extends IdentifiableObject> void preDelete( T persistedObject, ObjectBundle bundle )
{
if ( !JobConfiguration.class.isInstance( persistedObject ) )
{
return;
}
schedulingManager.stopJob( (JobConfiguration) persistedObject );
sessionFactory.getCurrentSession().delete( persistedObject );
}
@Override
public <T extends IdentifiableObject> void postCreate( T persistedObject, ObjectBundle bundle )
{
if ( !JobConfiguration.class.isInstance( persistedObject ) )
{
return;
}
JobConfiguration jobConfiguration = (JobConfiguration) persistedObject;
if ( jobConfiguration.getJobStatus() != DISABLED )
{
schedulingManager.scheduleJob( jobConfiguration );
}
}
@Override
public <T extends IdentifiableObject> void postUpdate( T persistedObject, ObjectBundle bundle )
{
if ( !JobConfiguration.class.isInstance( persistedObject ) )
{
return;
}
JobConfiguration jobConfiguration = (JobConfiguration) persistedObject;
if ( jobConfiguration.getJobStatus() != DISABLED )
{
schedulingManager.scheduleJob( jobConfiguration );
}
}
}
|
/*
* University of Saskatchewan
* Computer Science
*
*/
package databaseinterface;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author ychen
*/
public class DatabaseInterface {
private final static String USER = "ychen";
private final static String PASS = "th0ught";
/**
* We have an empty constructor so someone doesn't accidentally instantiate this class
*/
public DatabaseInterface(){}
/**
* Internal method only. Cannot be called otherwise.
* Obtains the number of rows returned in the query.
* result should always be not null. But in the off chance that it is, it will return -1
* @param result the result set of a query
* @return the size of the result set
*/
private static int getResultSize(ResultSet result){
try{
result.last();
int size = result.getRow();
// we must reset the cursor to the beginning before returning
result.beforeFirst();
return size;
}
catch (SQLException e){
System.err.println("ERROR: " + e.getMessage());
return -1;
}
}
public static Connection instantiateConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://projectindigo.ca:3306", USER, PASS);
}
catch (SQLException e){
System.err.println("ERROR: " + e.getMessage());
return null;
}
catch (ClassNotFoundException e){
return null;
}
}
public static String [] getDeviceList(Connection conn) throws IllegalStateException{
if (conn == null) throw new IllegalStateException("ERROR: The connection was not instantiated or dropped!");
String [] r = null;
try {
ResultSet result = conn.createStatement().executeQuery("SELECT DISTINCT device_id FROM bigbrother.gps_data");
int size = getResultSize(result);
r = new String[size];
for (int i=0; i<size; i++){
result.next();
r[i] = result.getString("device_id");
}
} catch (SQLException e) {
System.err.println("ERROR: " + e.getMessage());
}
return r;
}
/**
* converts a given integer epoch representation of the date into a human readable format
* Format: MM/DD|24Hour:Min:Sec -- e.g. 03/20|23:59:55
* @param epoch the UNIX epoch representation of the time
* @return a string representation of the time formated as above
*/
private static String convertEpochToReadable(int epoch){
// TODO write this method
return null; // remove this when finished writing. Only here to prevent compiler errors
}
/**
* Queries the database to obtain ALL timestamp and GPS coordinates for a specific device_id.
* @param conn An already instantiated connection.
* @param device_id The string representation of the device_id column
* @return An array of triples (GPSSet) containing <Time, Longitude, Latitude> ordered ascending by time
* NOTE: Time is a readable string representation of the time. Do NOT use epoch time to store.
* Time format should be: MM/DD|24Hour:Min:Sec (complete the conversion method first
*
* Columns: Time = time | longitude = longitude | latitude = lat
*/
public static GPSSet<String, BigDecimal, BigDecimal> [] getAllCoordinates(Connection conn, String device_id){
// TODO write this method
return null; // remove this when finished writing. Only here to prevent compiler errors
}
public static void destroyConnection(Connection conn){
try{
conn.close();
}
catch (SQLException e){
System.err.println("ERROR: " + e.getMessage());
}
catch (Exception e){
System.err.println("ERROR: " + e.getMessage());
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
DatabaseInterface d = new DatabaseInterface();
Connection conn = instantiateConnection();
String [] r = getDeviceList(conn);
destroyConnection(conn);
if (r != null){
for (String i : r){
System.out.println(i);
}
}
}
}
|
package org.innovateuk.ifs.application.feedback.viewmodel;
import org.innovateuk.ifs.application.finance.viewmodel.ApplicationFinanceSummaryViewModel;
import org.innovateuk.ifs.application.finance.viewmodel.ApplicationFundingBreakdownViewModel;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.assessment.resource.ApplicationAssessmentAggregateResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.form.resource.SectionResource;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
public class ApplicationFeedbackViewModel {
private final ApplicationResource application;
private final CompetitionResource competition;
private final OrganisationResource leadOrganisation;
private final List<OrganisationResource> applicationOrganisations;
private final BigDecimal totalFundingSought;
private final List<String> feedback;
private final boolean hasFinanceSection;
private final Map<Long, SectionResource> sections;
private final Map<Long, List<QuestionResource>> sectionQuestions;
private final ApplicationAssessmentAggregateResource scores;
private final ApplicationFinanceSummaryViewModel applicationFinanceSummaryViewModel;
private final ApplicationFundingBreakdownViewModel applicationFundingBreakdownViewModel;
private final InterviewFeedbackViewModel interviewFeedbackViewModel;
private final long applicationTermsQuestionId;
private final boolean projectWithdrawn;
private final boolean collaborativeProject;
public ApplicationFeedbackViewModel(ApplicationResource application,
CompetitionResource competition,
OrganisationResource leadOrganisation,
List<OrganisationResource> applicationOrganisations,
BigDecimal totalFundingSought,
List<String> feedback,
boolean hasFinanceSection,
Map<Long, SectionResource> sections,
Map<Long, List<QuestionResource>> sectionQuestions,
ApplicationAssessmentAggregateResource scores,
ApplicationFinanceSummaryViewModel applicationFinanceSummaryViewModel,
ApplicationFundingBreakdownViewModel applicationFundingBreakdownViewModel,
InterviewFeedbackViewModel interviewFeedbackViewModel,
long applicationTermsQuestionId,
boolean projectWithdrawn,
boolean collaborativeProject) {
this.application = application;
this.competition = competition;
this.leadOrganisation = leadOrganisation;
this.applicationOrganisations = applicationOrganisations;
this.totalFundingSought = totalFundingSought;
this.feedback = feedback;
this.hasFinanceSection = hasFinanceSection;
this.sections = sections;
this.sectionQuestions = sectionQuestions;
this.scores = scores;
this.applicationFinanceSummaryViewModel = applicationFinanceSummaryViewModel;
this.applicationFundingBreakdownViewModel = applicationFundingBreakdownViewModel;
this.interviewFeedbackViewModel = interviewFeedbackViewModel;
this.applicationTermsQuestionId = applicationTermsQuestionId;
this.projectWithdrawn = projectWithdrawn;
this.collaborativeProject = collaborativeProject;
}
public ApplicationResource getApplication() {
return application;
}
public CompetitionResource getCompetition() {
return competition;
}
public OrganisationResource getLeadOrganisation() {
return leadOrganisation;
}
public List<OrganisationResource> getApplicationOrganisations() {
return applicationOrganisations;
}
public BigDecimal getTotalFundingSought() {
return totalFundingSought;
}
public List<String> getFeedback() {
return feedback;
}
public boolean isHasFinanceSection() {
return hasFinanceSection;
}
public Map<Long, SectionResource> getSections() {
return sections;
}
public Map<Long, List<QuestionResource>> getSectionQuestions() {
return sectionQuestions;
}
public ApplicationAssessmentAggregateResource getScores() {
return scores;
}
public ApplicationFinanceSummaryViewModel getApplicationFinanceSummaryViewModel() {
return applicationFinanceSummaryViewModel;
}
public ApplicationFundingBreakdownViewModel getApplicationFundingBreakdownViewModel() {
return applicationFundingBreakdownViewModel;
}
public InterviewFeedbackViewModel getInterviewFeedbackViewModel() {
return interviewFeedbackViewModel;
}
public long getApplicationTermsQuestionId() {
return applicationTermsQuestionId;
}
public boolean isProjectWithdrawn() {
return projectWithdrawn;
}
public boolean isCollaborativeProject() {
return collaborativeProject;
}
}
|
package verification.platu.MDD;
import java.util.*;
import lpn.parser.Transition;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
public class mddNode {
static int blockSize = 8;
static int numBlocks = 16;
static int blockIdxMask = 15;
static int arrayIdxoffset = 4;
int level;
private mddNode[][] nodeMap;
private int[] blkHashVal;
int refCount;
int hashVal;
int nodeMapSize;
int maxArrayBound;
public mddNode() {
this.reset();
}
public mddNode(int thisLevel) {
this.reset();
level = thisLevel;
}
private void reset() {
level = -1;
nodeMap = new mddNode[numBlocks][blockSize];
this.blkHashVal = new int[numBlocks];
for(int i = 0; i < numBlocks; i++){
this.nodeMap[i] = null;
this.blkHashVal[i] = 0;
}
refCount = 0;
hashVal = 0;
nodeMapSize = 0;
maxArrayBound = -1;
}
private mddNode split() {
mddNode copy = new mddNode();
copy.level = this.level;
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++) {
mddNode succ = this.getSucc(blkIter, arrayIter);
if(succ != null)
copy.addSucc(blkIter, arrayIter, succ);
}
copy.blkHashVal[blkIter] = this.blkHashVal[blkIter];
}
copy.refCount = 0;
copy.hashVal = this.hashVal;
return copy;
}
/**
* Add an integer tuple into MDD root at this node.
* Isomorphic nodes are not shared.
*
* @param idxArray
* @return null if input idxArray is added into the MDD, root node otherwise.
*/
public mddNode add(int[] idxArray) {
if(this.level == -1) {
System.out.println("level is not right 1");
System.exit(0);
}
int curIdx = idxArray[this.level];
int stateIdx = curIdx;
int blockIdx = stateIdx & this.blockIdxMask;
int arrayIdx = stateIdx >> this.arrayIdxoffset;
mddNode nextNode = this.getSucc(blockIdx, arrayIdx);
if(nextNode == null) {
if(this.level == idxArray.length-1) {
this.addSucc(blockIdx, arrayIdx, Mdd.terminal);
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
return null;
}
else {
nextNode = new mddNode();
nextNode.level = this.level + 1;
nextNode.add(idxArray);
this.addSucc(blockIdx, arrayIdx, nextNode);
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
return null;
}
}
else {
if(nextNode == Mdd.terminal)
return this;
else if(nextNode.add(idxArray)==null)
return null;
return this;
}
}
public mddNode add(int[] idxArray, HashMap<mddNode, mddNode>[] nodeTbl, int shrLevel) {
if(this.level == -1) {
System.out.println("level is not right 1");
System.exit(0);
}
int curIdx = idxArray[this.level];
int stateIdx = curIdx;
int blockIdx = stateIdx & this.blockIdxMask;
int arrayIdx = stateIdx >> this.arrayIdxoffset;
mddNode nextNode = this.getSucc(blockIdx, arrayIdx);
if(nextNode == null) {
if(this.level == idxArray.length-1) {
nodeTbl[this.level].remove(this);
this.addSucc(blockIdx, arrayIdx, Mdd.terminal);
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
mddNode newThisNode = nodeTbl[this.level].get(this);
if(newThisNode != null) {
return newThisNode;
}
nodeTbl[this.level].put(this, this);
return this;
}
else {
nextNode = new mddNode();
nextNode.level = this.level + 1;
mddNode newNextNode = nextNode.add(idxArray, nodeTbl, shrLevel);
if(newNextNode != nextNode)
nextNode = newNextNode;
nextNode.refCount++;
if(level < shrLevel)
nodeTbl[this.level].remove(this);
this.addSucc(blockIdx, arrayIdx, nextNode);
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
if(level < shrLevel) {
mddNode newThis = nodeTbl[this.level].get(this);
if (newThis != null) {
for(int blkIter = 0; blkIter < this.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++)
if(this.nodeMap[blkIter][arrayIter] != null)
this.nodeMap[blkIter][arrayIter].refCount
}
return newThis;
}
nodeTbl[this.level].put(this, this);
}
return this;
}
}
else if(nextNode == Mdd.terminal) {
//System.out.println("mddNode: should not reach here. Abort!");
//System.exit(0);
return Mdd.terminal;
}
else {
mddNode newNextNode = nextNode;
if(nextNode.refCount > 1) {
newNextNode = nextNode.split();//new mddNode(nextNode);
nextNode.refCount
// for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
// if(nextNode.nodeMap[blkIter] == null)
// continue;
// for(int arrayIter = 0; arrayIter < nextNode.nodeMap[blkIter].length; arrayIter++)
// if(nextNode.nodeMap[blkIter][arrayIter] != null)
// nextNode.nodeMap[blkIter][arrayIter].refCount++;
mddNode newNextNode_1 = newNextNode.add(idxArray, nodeTbl, shrLevel);
if (newNextNode_1 != newNextNode)
newNextNode = newNextNode_1;
}
else {
newNextNode = nextNode.add(idxArray, nodeTbl, shrLevel);
// if no next node is splitted and the next node does not have equivalent,
// do nothing further.
if(newNextNode == nextNode)
return this;
nextNode.refCount
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(nextNode.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < nextNode.nodeMap[blkIter].length; arrayIter++)
if(nextNode.nodeMap[blkIter][arrayIter] != null)
nextNode.nodeMap[blkIter][arrayIter].refCount++;
}
}
if(level < shrLevel)
nodeTbl[this.level].remove(this);
newNextNode.refCount++;
this.addSucc(blockIdx, arrayIdx, newNextNode);
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
if(level < shrLevel) {
mddNode newThis = nodeTbl[this.level].get(this);
if (newThis != null) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++)
if(this.nodeMap[blkIter][arrayIter] != null)
this.nodeMap[blkIter][arrayIter].refCount
}
return newThis;
}
nodeTbl[this.level].put(this, this);
}
return this;
}
}
public static int numCalls = 0;
public static int cacheNodes = 0;
public static int splits_level1 = 0;
public static int splits_level2 = 0;
public static int splits_level3 = 0;
public mddNode union(final mddNode other, HashMap<mddNode, mddNode>[] nodeTbl, HashMap<mddNode, HashMap<mddNode, mddNode>> unionCache) {
numCalls++;
mddNode thisCopy = this.split();
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(other.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < other.nodeMap[blkIter].length; arrayIter++) {
mddNode thisSucc = this.getSucc(blkIter, arrayIter);
mddNode otherSucc = other.getSucc(blkIter, arrayIter);
if(otherSucc == null)
continue;
if(thisSucc == null) {
thisCopy.addSucc(blkIter, arrayIter, otherSucc);
continue;
}
// When successors are terminals, return.
if(thisSucc == Mdd.terminal || otherSucc == Mdd.terminal)
continue;
if(thisSucc==otherSucc || otherSucc.subSet(thisSucc) == true)
continue;
mddNode succCached = null;
HashMap<mddNode, mddNode> second = unionCache.get(thisSucc);
if(second != null) {
succCached = second.get(otherSucc);
}
if(succCached == null) {
mddNode succUnion = thisSucc.union(otherSucc, nodeTbl, unionCache);
// Add newSucc into the cache to avoid call union(thisSuccOriginal, otherSucc) again.
HashMap<mddNode, mddNode> secondCache = unionCache.get(thisSucc);
cacheNodes++;
if(secondCache == null) {
secondCache = new HashMap<mddNode, mddNode>();
secondCache.put(otherSucc, succUnion);
unionCache.put(thisSucc, secondCache);
}
else
secondCache.put(otherSucc, succUnion);
succCached = succUnion;
}
thisSucc.remove(nodeTbl);
thisCopy.addSucc(blkIter, arrayIter, succCached);
}
}
mddNode result = nodeTbl[thisCopy.level].get(thisCopy);
if(result == null) {
nodeTbl[thisCopy.level].put(thisCopy, thisCopy);
return thisCopy;
}
thisCopy.remove(nodeTbl);
return result;
}
public mddNode compress(HashMap<mddNode, mddNode>[] nodeTbl) {
int mddHeight = nodeTbl.length;
if(this.level < mddHeight-1) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++) {
mddNode nextNode = this.nodeMap[blkIter][arrayIter];
if(nextNode == null)
continue;
mddNode newNextNode = nextNode.compress(nodeTbl);
if(newNextNode != nextNode) {
this.addSucc(blkIter, arrayIter, newNextNode);
}
}
}
}
mddNode newThis = nodeTbl[this.level].get(this);
if(newThis == null) {
nodeTbl[this.level].put(this, this);
return this;
}
else if(newThis != this)
return newThis;
return this;
}
/*
* Recursively remove this nodes and its successor nodes from nodeTbl if their reference
* count is 0.
*/
public void remove(HashMap<mddNode, mddNode>[] nodeTbl) {
int mddHeight = nodeTbl.length;
this.refCount
if(this.refCount > 0)
return;
if(this.level < mddHeight) {
if(this.level < mddHeight - 1) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++) {
mddNode thisSucc = this.getSucc(blkIter, arrayIter);
if(thisSucc == null)
continue;
thisSucc.remove(nodeTbl);
}
}
}
nodeTbl[this.level].remove(this);
}
}
/**
* Check if stateArray already exists in MDD.
* @param stateArray
* @param index
* @param terminal
* @return true if stateArray exists in MDD, false otherwise.
*/
public mddNode contains(int[] idxArray) {
if(this.level == -1) {
System.out.println("level is not right 2");
System.exit(0);
}
int curIdx = idxArray[this.level];
int blockIdx = curIdx & mddNode.blockIdxMask;
int arrayIdx = curIdx >> mddNode.arrayIdxoffset;
mddNode nextNode = this.getSucc(blockIdx, arrayIdx);
if (nextNode == null)
return null;
if (nextNode == Mdd.terminal)
return Mdd.terminal;
return nextNode.contains(idxArray);
}
/*
* Exhaustively fire all local LPN transitions from each local state in curStateArray
*/
public mddNode doLocalFirings(StateGraph[] curLpnArray, State[] curStateArray,
LinkedList<State>[] nextSetArray,
mddNode reachSet,
HashMap<mddNode, mddNode>[] nodeTbl) {
int curBlkIdx = curStateArray[this.level].getIndex() & mddNode.blockIdxMask;
int curArrayIdx = curStateArray[this.level].getIndex() >> mddNode.arrayIdxoffset;
mddNode succ = Mdd.terminal;
if(this.level == curLpnArray.length - 1) {
this.addSucc(curBlkIdx, curArrayIdx, succ);
}
else if(this.level < curLpnArray.length) {
succ = new mddNode();
succ.level = this.level + 1;
mddNode newSucc = succ.doLocalFirings(curLpnArray, curStateArray, nextSetArray, reachSet, nodeTbl);
this.addSucc(curBlkIdx, curArrayIdx, newSucc);
succ = newSucc;
}
/*
* Do exhaustive local firings at this level.
*/
StateGraph curLpn = curLpnArray[this.level];
State curState = curStateArray[this.level];
// HashMap<State, State> curLocalStateSet = localStateSets[this.level];
nextSetArray[this.level].addLast(curState);
LinkedList<Transition> curEnabled = curLpn.getEnabled(curState);
LinkedList<Transition> localTranSet = new LinkedList<Transition>();
if(curEnabled != null) {
for(Transition firedTran : curEnabled)
if(firedTran.isLocal()==true)
localTranSet.addLast(firedTran);
}
if(localTranSet.size() == 0) {
mddNode newThis = nodeTbl[this.level].get(this);
if(newThis == null) {
nodeTbl[this.level].put(this, this);
return this;
}
this.remove(nodeTbl);
return newThis;
}
HashSet<State> curLocalNewStates = new HashSet<State>();
Stack<State> stateStack = new Stack<State>();
Stack<LinkedList<Transition>> enabledStack = new Stack<LinkedList<Transition>>();
stateStack.push(curState);
enabledStack.push(localTranSet);
LinkedList<State[]> nextSet_tmp = new LinkedList<State[]>();
while(stateStack.size() != 0) {
curState = stateStack.pop();
LinkedList<Transition> curLocalEnabled = enabledStack.pop();
for(Transition tran2fire : curLocalEnabled) {
//System.out.println("tran2fire = " + tran2fire.getLabel() + " in curlocalState = " + curState.getLabel());
// TODO: Need to fix this.
State nextState = null; //tran2fire.fire(curLpnArray[tran2fire.getLpn().getIndex()], curState);
// System.out.println("1 nextLocalState = " + nextState.getLabel());
if(curLocalNewStates.contains(nextState) == true)
continue;
// System.out.println("2 nextLocalState = " + nextState.getLabel());
curEnabled = curLpn.getEnabled(curState);
LinkedList<Transition> nextEnabled = curLpn.getEnabled(nextState);
// TODO: Need to fix this.
Transition disabledTran = null; //tran2fire.disablingError(curEnabled, nextEnabled);
if(disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ tran2fire.getFullLabel() + "!");
System.exit(0);
}
//System.out.println("addlocal nextLocalState = " + nextState.getLabel());
curLocalNewStates.add(nextState);
int nextBlkIdx = nextState.getIndex() & mddNode.blockIdxMask;
int nextArrayIdx = nextState.getIndex() >> mddNode.arrayIdxoffset;
this.addSucc(nextBlkIdx, nextArrayIdx, succ);
LinkedList<Transition> nextLocalEnabled = new LinkedList<Transition>();
boolean nonLocalNext = false;
for(Transition tran : nextEnabled) {
if(tran.isLocal()==true)
nextLocalEnabled.addLast(tran);
else
nonLocalNext = true;
}
nextState.hasNonLocalEnabled(nonLocalNext);
nextSetArray[this.level].addLast(nextState);
if(nextLocalEnabled.size() == 0)
continue;
stateStack.push(nextState);
enabledStack.push(nextLocalEnabled);
//System.out.println("added state " + nextState.getLabel() + " into localNewStateSet");
// for(int i = 0; i < curStateArray.length; i++)
// System.out.print(newNextStateArray[i].getLabel()+", ");
// System.out.println("\n
}
}
mddNode newThis = nodeTbl[this.level].get(this);
if(newThis == null) {
nodeTbl[this.level].put(this, this);
return this;
}
this.remove(nodeTbl);
return newThis;
}
/*
* Return the successor node with index exists in nodeMap.
*/
private mddNode getSucc(int blockIdx, int arrayIdx) {
if(this.nodeMap[blockIdx]==null || arrayIdx >= this.nodeMap[blockIdx].length)
return null;
return this.nodeMap[blockIdx][arrayIdx];
}
/*
* Insert a succNode with index into the nodeMap, whose size is automatically adjusted.
*/
private boolean addSucc(int blockIdx, int arrayIdx, mddNode succNode) {
int oldsize = nodeMap.length;
boolean newState = false;
if(this.nodeMap[blockIdx]==null || arrayIdx >= this.nodeMap[blockIdx].length) {
this.resizeNodeMap(blockIdx, arrayIdx);
newState = true;
//System.out.println(this + " >>> node level = " + level + " state label = " + index + " " + oldsize + " " + this.nodeMap.length);
}
this.nodeMap[blockIdx][arrayIdx] = succNode;
succNode.refCount++;
this.blkHashVal[blockIdx] = Integer.rotateLeft(Arrays.hashCode(this.nodeMap[blockIdx]), this.level);
this.hashVal = 0;
nodeMapSize++;
return true;
}
/*
* Resize the nodeMap so that an element with 'index' can be inserted into the nodeMap.
*/
private void resizeNodeMap(int blockIdx, int arrayIdx) {
if(this.nodeMap[blockIdx] == null) {
int newBlockSize = (arrayIdx / mddNode.blockSize + 1) * mddNode.blockSize;
try {
this.nodeMap[blockIdx] = new mddNode[newBlockSize];
for (int i = 0; i < newBlockSize; i++) {
this.nodeMap[blockIdx][i] = null;
}
} catch (Exception e) {
String errorMessage = String.format(
"blockIdx=%s, arrayIdx=%s, newBlockSize=%s\n",
blockIdx, arrayIdx,newBlockSize);
throw new RuntimeException(errorMessage, e);
}
}
else if(arrayIdx >= this.nodeMap[blockIdx].length) {
int newBlockSize = (arrayIdx / mddNode.blockSize + 1) * mddNode.blockSize;
mddNode[] newBlock = new mddNode[newBlockSize];
for(int i = 0; i < newBlock.length; i++) {
if(i < this.nodeMap[blockIdx].length)
newBlock[i] = this.nodeMap[blockIdx][i];
else
newBlock[i] = null;
}
this.nodeMap[blockIdx] = newBlock;
}
}
@Override
public boolean equals(Object other) {
mddNode otherNode = (mddNode)other;
if(level != otherNode.level)
return false;
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null && otherNode.nodeMap[blkIter] == null)
continue;
if(this.nodeMap[blkIter] == null && otherNode.nodeMap[blkIter] != null)
return false;
if(this.nodeMap[blkIter] != null && otherNode.nodeMap[blkIter] == null)
return false;
if(this.nodeMap[blkIter].length != otherNode.nodeMap[blkIter].length)
return false;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++)
if(this.nodeMap[blkIter][arrayIter] != otherNode.nodeMap[blkIter][arrayIter])
return false;
}
return true;
}
public int hashCode() {
if(hashVal == 0)
hashVal = Arrays.hashCode(this.blkHashVal);
return hashVal;
}
public boolean subSet(mddNode other) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(other.nodeMap[blkIter] == null && this.nodeMap[blkIter] != null)
return false;
if(this.nodeMap[blkIter] == null)
continue;
if(this.nodeMap[blkIter].length > other.nodeMap[blkIter].length)
return false;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++) {
mddNode thisSucc = this.getSucc(blkIter, arrayIter);
mddNode otherSucc = other.getSucc(blkIter, arrayIter);
if(thisSucc != null && otherSucc == null)
return false;
if(thisSucc != otherSucc)
return false;
}
}
return true;
}
public int[] next(int mddHeight) {
if(maxArrayBound == -1) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++)
if(this.nodeMap[blkIter] != null && this.nodeMap[blkIter].length > maxArrayBound)
maxArrayBound = this.nodeMap[blkIter].length;
}
for(int arrayIter = 0; arrayIter < maxArrayBound; arrayIter++) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
mddNode thisSucc = this.getSucc(blkIter, arrayIter);
if(thisSucc == null)
continue;
if(this.level == mddHeight-1) {
int stateIdx = (arrayIter << mddNode.arrayIdxoffset) | blkIter;
int[] result = new int[mddHeight];
result[this.level] = stateIdx;
return result;
}
int[] tmp = thisSucc.next(mddHeight);
if(tmp == null)
continue;
int stateIdx = (arrayIter << mddNode.arrayIdxoffset) | blkIter;
tmp[this.level] = stateIdx;
return tmp;
}
}
return null;
}
public int[] next(int mddHeight, int[] curIdxArray) {
int curIdx = curIdxArray[this.level];
// Find the largest array bound.
if(maxArrayBound == -1) {
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++)
if(this.nodeMap[blkIter] != null && this.nodeMap[blkIter].length > maxArrayBound)
maxArrayBound = this.nodeMap[blkIter].length;
}
if(this.level == mddHeight-1) {
int newIdx = curIdx + 1;
int newBlkIdx = newIdx & mddNode.blockIdxMask;
int newArrayIdx = newIdx >> mddNode.arrayIdxoffset;
for(int arrayIter = newArrayIdx; arrayIter < maxArrayBound; arrayIter++) {
int startingBlkIdx = (arrayIter > newArrayIdx) ? 0 : newBlkIdx;
for(int blkIter = startingBlkIdx; blkIter < mddNode.numBlocks; blkIter++) {
// if(this.nodeMap[blkIter] == null)
// continue;
mddNode thisSucc = this.getSucc(blkIter, arrayIter);
if(thisSucc == null)
continue;
int stateIdx = (arrayIter << mddNode.arrayIdxoffset) | blkIter;
int[] result = new int[mddHeight];
result[this.level] = stateIdx;
return result;
}
}
return null;
}
else {
int curBlkIdx = curIdx & mddNode.blockIdxMask;
int curArrayIdx = curIdx >> mddNode.arrayIdxoffset;
mddNode thisSucc = this.getSucc(curBlkIdx, curArrayIdx);
int[] tmp = thisSucc.next(mddHeight, curIdxArray);
if(tmp != null) {
tmp[this.level] = curIdx;
return tmp;
}
int newIdx = curIdx + 1;
int newBlkIdx = newIdx & mddNode.blockIdxMask;
int newArrayIdx = newIdx >> mddNode.arrayIdxoffset;
for(int arrayIter = newArrayIdx; arrayIter < maxArrayBound; arrayIter++) {
int startingBlkIdx = (arrayIter > newArrayIdx) ? 0 : newBlkIdx;
for(int blkIter = startingBlkIdx; blkIter < mddNode.numBlocks; blkIter++) {
// if(this.nodeMap[blkIter] == null)
// continue;
thisSucc = this.getSucc(blkIter, arrayIter);
if(thisSucc == null)
continue;
int stateIdx = (arrayIter << mddNode.arrayIdxoffset) | blkIter;
int[] result = thisSucc.next(mddHeight);
result[this.level] = stateIdx;
return result;
}
}
return null;
}
}
public void increaseRefCnt() {
refCount++;
}
public void decreaseRefCnt() {
if(refCount == 1) {
System.out.println("Cannot decrease the ref count of 1");
System.exit(0);
}
refCount
}
public int getRefCount() {
return refCount;
}
public int getSuccSize() {
return nodeMap.length;
}
public double pathCount(HashSet<mddNode> uniqueNodes) {
uniqueNodes.add(this);
double paths = 0.0;
if(this == Mdd.terminal)
return paths;
for(int blkIter = 0; blkIter != mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < this.nodeMap[blkIter].length; arrayIter++) {
if(this.nodeMap[blkIter][arrayIter] == null)
continue;
if(this.nodeMap[blkIter][arrayIter] == Mdd.terminal)
paths += 1;
else
paths += nodeMap[blkIter][arrayIter].pathCount(uniqueNodes);
}
}
return paths;
}
public void print() {
if(nodeMap.length == 0)
return;
for(int blkIter = 0; blkIter < mddNode.numBlocks; blkIter++) {
if(this.nodeMap[blkIter] == null)
continue;
for(int arrayIter = 0; arrayIter < nodeMap[blkIter].length; arrayIter++) {
if(this.nodeMap[blkIter][arrayIter] == null)
continue;
System.out.println(this + " level = " + level + ", " + (blkIter + (arrayIter << this.arrayIdxoffset)) + " -> " + nodeMap[blkIter][arrayIter] + " refCount = " + nodeMap[blkIter][arrayIter].refCount);
nodeMap[blkIter][arrayIter].print();
}
}
}
}
|
package org.jkiss.dbeaver.ext.postgresql.model.impls.greenplum;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreDataSource;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreServerExtension;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreTableBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.jkiss.dbeaver.ext.postgresql.model.impls.greenplum.GreenplumWithClauseBuilder.generateWithClause;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class GreenplumWithClauseBuilderTest {
@Mock
private GreenplumTable table;
@Mock
private PostgreTableBase tableBase;
@Mock
private PostgreDataSource dataSource;
@Mock
private PostgreServerExtension serverExtension;
@Test
public void generateWithClause_whenTableWithoutOidsAndWithOptions_shouldDisplayWithClauseWithRelOptions() {
setupGeneralWhenMocks(false, false);
when(tableBase.getRelOptions()).thenReturn(new String[]{"appendonly=true"});
String withClause = generateWithClause(table, tableBase);
assertEquals("\nWITH (\n\tappendonly=true\n)", withClause);
}
@Test
public void generateWithClause_whenTableWithOidsAndOptions_shouldDisplayWithClauseWithOidsAndOptions() {
setupGeneralWhenMocks(true, true);
when(tableBase.getRelOptions()).thenReturn(new String[]{"appendonly=true"});
String withClause = generateWithClause(table, tableBase);
assertEquals("\nWITH (\n\tOIDS=TRUE, appendonly=true\n)", withClause);
}
@Test
public void generateWithClause_whenTableWithoutOidsAndWithoutOptions_shouldNotDisplayWithClause() {
setupGeneralWhenMocks(false, false);
when(tableBase.getRelOptions()).thenReturn(null);
String withClause = generateWithClause(table, tableBase);
assertEquals("", withClause);
}
@Test
public void generateWithClause_whenTableWithOidsWithoutOptions_shouldDisplayWithClauseWithOids() {
setupGeneralWhenMocks(true, true);
when(tableBase.getRelOptions()).thenReturn(null);
String withClause = generateWithClause(table, tableBase);
assertEquals("\nWITH (\n\tOIDS=TRUE\n)", withClause);
}
@Test
public void generateWithClause_whenTableWithOidsWithMultipleOptions_shouldDisplayWithClauseWithOidsAndAllTheOptions() {
setupGeneralWhenMocks(true, true);
when(tableBase.getRelOptions()).thenReturn(new String[]{"appendonly=true", "orientation=column"});
String withClause = generateWithClause(table, tableBase);
assertEquals("\nWITH (\n\tOIDS=TRUE, appendonly=true, orientation=column\n)", withClause);
}
private void setupGeneralWhenMocks(boolean supportOids, boolean hasOids) {
when(serverExtension.supportsOids()).thenReturn(supportOids);
when(dataSource.getServerType()).thenReturn(serverExtension);
when(table.getDataSource()).thenReturn(dataSource);
when(table.isHasOids()).thenReturn(hasOids);
}
}
|
package org.camunda.bpm.qa.upgrade.scenarios7110.removaltime;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Date;
import java.util.List;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
/**
* @author Tassilo Weidner
*/
public class RemovalTimeBatchTest {
@Rule
public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.cfg.xml");
protected HistoryService historyService;
@Before
public void assignService() {
historyService = engineRule.getHistoryService();
}
@Test
public void shouldSetRemovalTimeForRootProcessInstanceOnly() {
// given
HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery()
.processInstanceBusinessKey("rootProcessInstance");
HistoricProcessInstance historicRootProcessInstance = query.singleResult();
HistoricProcessInstance historicChildProcessInstance = historyService.createHistoricProcessInstanceQuery()
.superProcessInstanceId(historicRootProcessInstance.getId())
.singleResult();
// assume
assertThat(historicRootProcessInstance.getRemovalTime(), nullValue());
assertThat(historicChildProcessInstance.getRemovalTime(), nullValue());
// when
syncExec(
historyService.setRemovalTimeToHistoricProcessInstances()
.byQuery(query)
.absoluteRemovalTime(new Date())
.hierarchical()
.executeAsync()
);
historicRootProcessInstance = query.singleResult();
historicChildProcessInstance = historyService.createHistoricProcessInstanceQuery()
.superProcessInstanceId(historicRootProcessInstance.getId())
.singleResult();
// then
assertThat(historicRootProcessInstance.getRemovalTime(), notNullValue());
assertThat(historicChildProcessInstance.getRemovalTime(), nullValue());
}
// helper ////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected void syncExec(Batch batch) {
String seedJobDefinitionId = batch.getSeedJobDefinitionId();
String jobId = engineRule.getManagementService().createJobQuery()
.jobDefinitionId(seedJobDefinitionId)
.singleResult()
.getId();
engineRule.getManagementService().executeJob(jobId);
String batchJobDefinitionId = batch.getBatchJobDefinitionId();
List<Job> jobs = engineRule.getManagementService().createJobQuery()
.jobDefinitionId(batchJobDefinitionId)
.list();
for (Job job : jobs) {
engineRule.getManagementService().executeJob(job.getId());
}
String monitorJobDefinitionId = batch.getMonitorJobDefinitionId();
jobId = engineRule.getManagementService().createJobQuery()
.jobDefinitionId(monitorJobDefinitionId)
.singleResult()
.getId();
engineRule.getManagementService().executeJob(jobId);
}
}
|
package est.sae.minesweeper;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import javax.swing.JFrame;
import est.sae.minesweeper.ButtonActions.actionTaken;
public class BaseWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 149684488393599155L;
private final String _HighScorePath = System.getProperty("user.dir") + "\\MineSweeperHighscores";
private JLabel _MinesLeft = new JLabel("0", SwingConstants.CENTER);
private JLabel _Counter = new JLabel("0", SwingConstants.CENTER);
private JPanel _InfoPanel = new JPanel();
private JMenuBar _MenuBar = new JMenuBar();
private JMenu _FileMenu = new JMenu("File");
private JMenu _HighscoreMenu = new JMenu("Highscores");
private JMenuItem _ChooseDifficulty = new JMenuItem("Choose Difficulty");
private JMenuItem _RestartGame = new JMenuItem("Restart Game");
private JMenuItem _LoadGame = new JMenuItem("Load Game");
private JMenuItem _SaveGame = new JMenuItem("Save Game");
private JMenuItem _ShowHighscore = new JMenuItem("Show Highscores");
private JMenuItem _DeleteHighscore = new JMenuItem("Delete Highscores");
private BasePanel _FieldPanel = new BeginnerPanel();
private BorderLayout _WindowLayout = new BorderLayout();
private BorderLayout _InfoLayout = new BorderLayout();
private Dimension _WindowSize = new Dimension(500, 600);
private JLabel _State = new JLabel();
private Timer _Timer = new Timer(1000, this);
private static enum _Difficulty {Beginner, Advanced, Professional};
private ArrayList<HighScore> _HighScores;
public BaseWindow()
{
// Call parent class for setting window name
super("Minesweeper");
FormatUI();
BuildMenu();
StartGame();
}
private void FormatUI() {
// Set initial window size and layout
this.setSize(_WindowSize);
this.setLayout(_WindowLayout);
// Formatting InfoPanel, used for displaying mines left and used time
_InfoPanel.setLayout(_InfoLayout);
_InfoPanel.setBorder(BorderFactory.createLoweredBevelBorder());
_MinesLeft.setPreferredSize(new Dimension(200, 100));
_Counter.setPreferredSize(new Dimension(200, 100));
_MinesLeft.setBorder(BorderFactory.createLineBorder(Color.BLACK));
_Counter.setBorder(BorderFactory.createLineBorder(Color.BLACK));
_InfoPanel.add(_MinesLeft, BorderLayout.LINE_START);
_InfoPanel.add(_Counter, BorderLayout.LINE_END);
this.add(_InfoPanel, BorderLayout.PAGE_START);
_State.setPreferredSize(new Dimension(this.getWidth(), 20));
this.add(_State, BorderLayout.SOUTH);
this.setJMenuBar(_MenuBar);
}
private void InitializeFieldPanel() {
// Formatting FieldPanel, used for displaying mine fields
_FieldPanel.setBorder(BorderFactory.createLoweredBevelBorder());
this.add(_FieldPanel, BorderLayout.CENTER);
}
public void InitializeMineCounter()
{
_MinesLeft.setText(String.valueOf(_FieldPanel.getMineCount()));
}
public void StartGame()
{
InitializeFieldPanel();
InitializeMineCounter();
_FieldPanel.RegenerateField();
_State.setText("Spiel luft");
_Counter.setText("0");
// Pack Frame to set window size to be big enough to set all components to their preferred size
this.pack();
this.setVisible(true);
_Timer.start();
}
public void StartSaveGame()
{
InitializeFieldPanel();
_State.setText("Spiel luft");
// Pack Frame to set window size to be big enough to set all components to their preferred size
this.pack();
this.setVisible(true);
_Timer.start();
}
public void LowerCounter()
{
_MinesLeft.setText(String.valueOf(Integer.parseInt(_MinesLeft.getText()) - 1));
}
public void RaiseCounter()
{
_MinesLeft.setText(String.valueOf(Integer.parseInt(_MinesLeft.getText()) + 1));
}
public static void main(String[] args) {
BaseWindow base = new BaseWindow();
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void BuildMenu()
{
_RestartGame.addActionListener(this);
_RestartGame.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F2, ActionEvent.ALT_MASK));
_ChooseDifficulty.addActionListener(this);
_ChooseDifficulty.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F3, ActionEvent.ALT_MASK));
_LoadGame.addActionListener(this);
_LoadGame.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F4, ActionEvent.ALT_MASK));
_SaveGame.addActionListener(this);
_SaveGame.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F5, ActionEvent.ALT_MASK));
_ShowHighscore.addActionListener(this);
_DeleteHighscore.addActionListener(this);
_FileMenu.add(_RestartGame);
_FileMenu.add(_ChooseDifficulty);
_FileMenu.add(_LoadGame);
_FileMenu.add(_SaveGame);
_HighscoreMenu.add(_ShowHighscore);
_HighscoreMenu.add(_DeleteHighscore);
_MenuBar.add(_FileMenu);
_MenuBar.add(_HighscoreMenu);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == _Timer)
{
_Counter.setText(String.valueOf(Integer.valueOf(_Counter.getText()) + 1));
}
else if(e.getSource() == _RestartGame)
{
StartGame();
}
else if(e.getSource() == _ChooseDifficulty)
{
DisplayDifficultyDialog();
}
else if(e.getSource() == _LoadGame)
{
LoadGame();
}
else if(e.getSource() == _SaveGame)
{
SaveGame();
}
else if(e.getSource() == _ShowHighscore)
{
ShowHighscore();
}
else if(e.getSource() == _DeleteHighscore)
{
DeleteHighscore();
}
}
private void ShowHighscore() {
LoadHighScore();
String scores = "Player Name" + "\t\t" + "Difficulty" + "\t\t" + "Time Needed" + "\t\t" + "Score" + "\n";
for(HighScore score : _HighScores)
{
scores += score.getPlayerName() + "\t\t" + score.getDifficulty() + "\t\t" + score.getTimeNeeded() + "\t\t" + score.getScore() + "\n";
}
JOptionPane.showMessageDialog(this, new JTextArea(scores));
}
private void DeleteHighscore() {
File highScore = new File(_HighScorePath);
if(highScore.exists())
{
highScore.delete();
}
}
private void CreateHighscoreEntry() {
File highScore = new File(_HighScorePath);
if(highScore.exists())
{
LoadHighScore();
}
String difficulty = "";
if(_FieldPanel instanceof BeginnerPanel)
{
difficulty = _Difficulty.Beginner.name();
}
else if(_FieldPanel instanceof AdvancedPanel)
{
difficulty = _Difficulty.Advanced.name();
}
else if(_FieldPanel instanceof ProfessionalPanel)
{
difficulty = _Difficulty.Professional.name();
}
String playerName = JOptionPane.showInputDialog(this, "Please enter your Name for your highscore entry!", "Annonymous");
if(playerName == null)
{
playerName = "Annonymous";
}
_HighScores = HighScore.AddNewEntry(_HighScores, playerName, difficulty, _FieldPanel.getRows(), _FieldPanel.getCols(), Integer.valueOf(_Counter.getText()));
SaveHighScores();
}
private void LoadHighScore() {
Object tempObj = null;
File score = new File(_HighScorePath);
if(!score.exists())
{
_HighScores = new ArrayList<HighScore>();
return;
}
try
{
FileInputStream fileIn = new FileInputStream(score);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
tempObj = objectIn.readObject();
objectIn.close();
fileIn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(tempObj instanceof ArrayList<?>)
{
_HighScores = (ArrayList<HighScore>) tempObj;
}
}
private void SaveHighScores() {
try
{
FileOutputStream fileOut = new FileOutputStream(_HighScorePath);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(_HighScores);
objectOut.flush();
objectOut.close();
fileOut.flush();
fileOut.close();
objectOut = null;
fileOut = null;
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
private void LoadGame() {
JFileChooser saveFileChooser = new JFileChooser();
saveFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int status = saveFileChooser.showOpenDialog(this);
if(status == 1)
{
return;
}
String filePath = saveFileChooser.getSelectedFile().getAbsolutePath();
JPanel tempInfoPanel = null;
BasePanel tempFieldPanel = null;
JLabel tempCounter = null;
JLabel tempMines = null;
try
{
FileInputStream fileIn = new FileInputStream(filePath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
tempInfoPanel = (JPanel) objectIn.readObject();
tempFieldPanel = (BasePanel) objectIn.readObject();
tempCounter = (JLabel) objectIn.readObject();
tempMines = (JLabel) objectIn.readObject();
objectIn.close();
fileIn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
_Timer.stop();
this.remove(_InfoPanel);
this.remove(_FieldPanel);
_InfoPanel = tempInfoPanel;
_FieldPanel = tempFieldPanel;
_Counter = tempCounter;
_MinesLeft = tempMines;
FormatUI();
StartSaveGame();
_InfoPanel.repaint();
_FieldPanel.repaint();
this.pack();
this.repaint();
}
public void SaveGame()
{
JFileChooser saveFileChooser = new JFileChooser();
saveFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int status = saveFileChooser.showOpenDialog(this);
if(status == 1)
{
return;
}
String filePath = saveFileChooser.getSelectedFile().getAbsolutePath();
filePath += "\\Test.txt";
try
{
FileOutputStream fileOut = new FileOutputStream(filePath);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(_InfoPanel);
objectOut.writeObject(_FieldPanel);
objectOut.writeObject(_Counter);
objectOut.writeObject(_MinesLeft);
objectOut.close();
fileOut.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
public void DisplayDifficultyDialog()
{
int n = JOptionPane.showOptionDialog(this,
"Please choose the difficulty you want to play.",
"Choose difficulty",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
_Difficulty.values(),
_Difficulty.Beginner);
switch (n)
{
case JOptionPane.YES_OPTION:
SetDifficulty(_Difficulty.Beginner);
break;
case JOptionPane.NO_OPTION:
SetDifficulty(_Difficulty.Advanced);
break;
case JOptionPane.CANCEL_OPTION:
SetDifficulty(_Difficulty.Professional);
break;
}
}
public void SetDifficulty(_Difficulty difficulty)
{
this.remove(_FieldPanel);
switch (difficulty)
{
case Beginner:
_FieldPanel = new BeginnerPanel();
break;
case Advanced:
_FieldPanel = new AdvancedPanel();
break;
case Professional:
_FieldPanel = new ProfessionalPanel();
break;
}
StartGame();
}
public void HaltGame()
{
_Timer.stop();
_FieldPanel.DisableAllButtons();
}
public void LostGame()
{
HaltGame();
_State.setText("Leider verloren!");
}
public void WinGame()
{
HaltGame();
CreateHighscoreEntry();
_State.setText("Gewonnen!");
}
public void ButtonActionOccured(MineButton buttonPressed, actionTaken pressed) {
boolean gameWon = false;
switch(pressed)
{
case PRESSED:
gameWon = _FieldPanel.ButtonWasUnhidden(buttonPressed);
break;
case FLAGGED:
gameWon = _FieldPanel.ButtonWasFlagged(buttonPressed);
break;
case UNFLAGGED:
_FieldPanel.ButtonWasUnflagged(buttonPressed);
}
if(gameWon)
{
WinGame();
}
}
public void EmptyButtonPressed(MineButton buttonPressed) {
_FieldPanel.UnveilAdjacentEmptyButtons(buttonPressed);
}
}
|
package com.uoit.freeroomfinder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
public class FreeRoom extends FreeRoomFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
private SearchTask searchTask = null;
private SharedPreferences sharedPrefs;
private Date curDate;
private Spinner timeSpinner;
/* Room search parameters */
private static String timePicked = "";
private static String datePicked = "";
private static String campusPicked = "";
private static int durationPicked = 0;
private static View rootView;
public static ArrayList<Rooms> availableRooms;
public FreeRoom() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootView = inflater.inflate(R.layout.activity_free_room, container, false);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity().getBaseContext());
curDate = new Date();
//Set up default values
Spinner campus = (Spinner)rootView.findViewById(R.id.campus);
campus.setSelection(Integer.valueOf(sharedPrefs.getString("default_campus", "0"))-1);
Spinner duration = (Spinner)rootView.findViewById(R.id.duration);
duration.setSelection(Integer.valueOf(sharedPrefs.getString("default_duration", "0"))-1);
timeSpinner = (Spinner)rootView.findViewById(R.id.time);
TextView date = (TextView)rootView.findViewById(R.id.date);
date.setText(MainActivity.datetimeFormater.formatDate(curDate) + " (Today)");
datePicked = MainActivity.datetimeFormater.formatDate(curDate);
availableRooms = new ArrayList<Rooms>();
date.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Date d = null;
try {
d = MainActivity.datetimeFormater.parseDate(datePicked);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
if(d != null)
{
c.setTime(d);
}
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
int dd = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog alert = new DatePickerDialog(rootView.getContext(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
datePicked = year + "-" + (monthOfYear+1) + "-" + dayOfMonth;
TextView date = (TextView)rootView.findViewById(R.id.date);
date.setText(datePicked);
if (datePicked.contains(MainActivity.datetimeFormater.formatDate(curDate))){
date.setText(datePicked + " (Today)");
}
}
}, yy, mm, dd);
alert.show();
}
});
Button search = (Button)rootView.findViewById(R.id.search);
search.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Date curDate = new Date();
Spinner timeSpinner = (Spinner)rootView.findViewById(R.id.time);
Spinner durationSpinner = (Spinner)rootView.findViewById(R.id.duration);
Spinner campusSpinner = (Spinner)rootView.findViewById(R.id.campus);
try
{
if (timeSpinner.getSelectedItem().toString().compareTo("Now") == 0)
{
timePicked = MainActivity.datetimeFormater.formatFullTime(MainActivity.datetimeFormater.formatTime(curDate));
}
else
{
timePicked = MainActivity.datetimeFormater.formatFullTime(timeSpinner.getSelectedItem().toString());
}
campusPicked = rootView.getResources().getStringArray(R.array.campus_names)[campusSpinner.getSelectedItemPosition()];
durationPicked = Integer.valueOf(durationSpinner.getSelectedItem().toString());
((MainActivity) FreeRoom.this.getActivity()).showProgress(true);
searchTask = new SearchTask();
searchTask.setOnFinshedTaskListener((Results)MainActivity
.switchTabs(MainActivity.RESULTS_TAB));
searchTask.execute();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
return rootView;
}
@Override
public void onResume()
{
super.onResume();
//Set up the time spinner to include the current time
int timeValues = R.array.time_values;
if(!sharedPrefs.getBoolean("army_clock", true))
{
timeValues = R.array.army_time_values;
}
ArrayList<String> spinnerArray = new ArrayList<String>(Arrays.asList(this.getResources().getStringArray(timeValues)));
spinnerArray.add(0, "Now");
ArrayAdapter<String> sa = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, spinnerArray);
sa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
timeSpinner.setAdapter(sa);
}
public class SearchTask extends AsyncTask<Void, Void, Boolean> {
private OnFinshedTaskListener listener;
@Override
protected Boolean doInBackground(Void... params) {
/* Get the list of available rooms and display the results */
availableRooms.clear();
availableRooms = Request.searchRooms(timePicked, datePicked, campusPicked, durationPicked);
for (Rooms room : availableRooms)
{
System.out.println(room.getRoom() + ", " + room.getStartTime() + ", " + room.getEndTime());
}
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
searchTask = null;
((MainActivity) FreeRoom.this.getActivity()).showProgress(false);
if (success) {
if(listener != null)
{
listener.onFinishedTaskListener();
}
} else {
//TODO show error if possible otherwise just remove todo
}
}
@Override
protected void onCancelled() {
searchTask = null;
((MainActivity) FreeRoom.this.getActivity()).showProgress(false);
}
public void setOnFinshedTaskListener(OnFinshedTaskListener listener){
this.listener = listener;
}
}
}
|
package org.eclipse.smarthome.binding.wemo.discovery;
import static org.eclipse.smarthome.binding.wemo.WemoBindingConstants.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.eclipse.smarthome.binding.wemo.handler.WemoHandler;
import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService;
import org.eclipse.smarthome.config.discovery.DiscoveryResult;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.io.net.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WemoDiscoveryService extends AbstractDiscoveryService {
private Logger logger = LoggerFactory.getLogger(WemoDiscoveryService.class);
/**
* Connection timeout
*/
private static int TIMEOUT = 5000;
/**
* Port to send discovery message to
*/
private static final int SSDP_PORT = 1900;
/**
* Port to use for sending discovery message
*/
private static final int SSDP_SEARCH_PORT = 1901;
/**
* Broadcast address to use for sending discovery message
*/
private static final String SSDP_IP = "239.255.255.250";
public InetAddress address;
/**
* When true we will keep sending out packets
*/
static boolean discoveryRunning = false;
/**
* The refresh interval for discovering WeMo devices
*/
private long refreshInterval = 600;
private ScheduledFuture<?> wemoDiscoveryJob;
private Runnable wemoDiscoveryRunnable = new Runnable() {
@Override
public void run() {
discoverWemo();
}
};
public WemoDiscoveryService() {
super(WemoHandler.SUPPORTED_THING_TYPES, 15, true);
}
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
return WemoHandler.SUPPORTED_THING_TYPES;
}
@Override
protected void startScan() {
logger.debug("Starting WeMo Device discovery");
discoverWemo();
}
@Override
protected void startBackgroundDiscovery() {
logger.trace("Start WeMo device background discovery");
if (wemoDiscoveryJob == null || wemoDiscoveryJob.isCancelled()) {
wemoDiscoveryJob = scheduler.scheduleAtFixedRate(wemoDiscoveryRunnable, 0, refreshInterval,
TimeUnit.SECONDS);
}
}
@Override
protected void stopBackgroundDiscovery() {
logger.debug("Stop WeMo device background discovery");
if (wemoDiscoveryJob != null && !wemoDiscoveryJob.isCancelled()) {
wemoDiscoveryJob.cancel(true);
wemoDiscoveryJob = null;
}
}
/**
* Scans for WeMo devices
*/
private synchronized void discoverWemo() {
logger.debug("Run Wemo device discovery");
sendWemoDiscoveryMessage();
logger.trace("Done sending WeMo broadcast discovery message");
// receiveWemoDiscoveryMessage();
logger.trace("Done receiving WeMo broadcast discovery message");
}
public void sendWemoDiscoveryMessage() {
logger.debug("wemoDiscovery() is called!");
try {
InetAddress localhost = InetAddress.getLocalHost();
InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);
InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);
// Request-Packet-Constructor
StringBuffer discoveryMessage = new StringBuffer();
discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
discoveryMessage.append("ST: upnp:rootdevice\r\n");
discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
discoveryMessage.append("MX: 5\r\n");
discoveryMessage.append("\r\n");
logger.trace("Request: {}", discoveryMessage.toString());
byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
dstAddress);
// Send multi-cast packet
MulticastSocket multicast = null;
try {
multicast = new MulticastSocket(null);
multicast.bind(srcAddress);
logger.trace("Source-Address = '{}'", srcAddress);
multicast.setTimeToLive(4);
logger.debug("Send multicast request.");
multicast.send(discoveryPacket);
} finally {
logger.trace("Multicast ends. Close connection.");
if (multicast != null) {
multicast.disconnect();
multicast.close();
}
}
// Response-Listener
DatagramSocket wemoReceiveSocket = null;
DatagramPacket receivePacket = null;
try {
wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT);
wemoReceiveSocket.setSoTimeout(TIMEOUT);
logger.debug("Send datagram packet.");
wemoReceiveSocket.send(discoveryPacket);
while (true) {
try {
receivePacket = new DatagramPacket(new byte[1536], 1536);
wemoReceiveSocket.receive(receivePacket);
final String message = new String(receivePacket.getData());
logger.trace("Received message: {}", message);
new Thread(new Runnable() {
@Override
public void run() {
String label = "WeMo Device";
String wemoUDN = null;
String wemoLocation = null;
String wemoFriendlyName = null;
String wemoModelName = null;
ThingUID uid = null;
if (message != null) {
if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
|| message.contains("Motion-1_0") || message.contains("Lightswitch-1_0")
|| message.contains("Sensor-1_0")) {
wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
"::upnp:rootdevice");
logger.debug("Wemo device with UDN '{}' found", wemoUDN);
wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
"/setup.xml");
if (wemoLocation != null) {
try {
int timeout = 5000;
String response = HttpUtil.executeUrl("GET",
wemoLocation + "/setup.xml", timeout);
wemoFriendlyName = StringUtils.substringBetween(response,
"<friendlyName>", "</friendlyName>");
logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
wemoLocation);
wemoModelName = StringUtils.substringBetween(response, "<modelName>",
"</modelName>");
logger.trace("Wemo device '{}' has model name '{}'", wemoFriendlyName,
wemoModelName);
label = "Wemo" + wemoModelName;
switch (wemoModelName) {
case "Socket":
logger.debug(
"Creating ThingUID for device model '{}' with UDN '{}'",
wemoModelName, wemoUDN);
uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);
break;
case "Insight":
logger.trace(
"Creating ThingUID for device model '{}' with UDN '{}'",
wemoModelName, wemoUDN);
uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
break;
case "LightSwitch":
logger.trace(
"Creating ThingUID for device model '{}' with UDN '{}'",
wemoModelName, wemoUDN);
uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
break;
case "Motion":
logger.trace(
"Creating ThingUID for device model '{}' with UDN '{}'",
wemoModelName, wemoUDN);
uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
break;
case "Sensor":
logger.trace(
"Creating ThingUID for device model '{}' with UDN '{}'",
wemoModelName, wemoUDN);
uid = new ThingUID(WEMO_SENSOR_TYPE_UID, wemoUDN);
break;
}
Map<String, Object> properties = new HashMap<>(4);
properties.put(UDN, wemoUDN);
properties.put(LOCATION, wemoLocation);
DiscoveryResult result = DiscoveryResultBuilder.create(uid)
.withProperties(properties).withLabel(label).build();
thingDiscovered(result);
} catch (Exception te) {
logger.error("Could not discover WeMo device", te);
}
}
}
}
}
}).start();
} catch (SocketTimeoutException e) {
logger.debug("Message receive timed out.");
break;
}
}
} finally {
if (wemoReceiveSocket != null) {
wemoReceiveSocket.disconnect();
wemoReceiveSocket.close();
}
}
} catch (Exception e) {
logger.error("Could not send Wemo device discovery", e);
}
}
}
|
package org.springframework.ide.vscode.boot.java;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.lsp4j.CompletionItemKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.boot.app.BootJavaConfig;
import org.springframework.ide.vscode.boot.app.BootLanguageServerParams;
import org.springframework.ide.vscode.boot.app.SpringSymbolIndex;
import org.springframework.ide.vscode.boot.java.annotations.AnnotationHierarchyAwareLookup;
import org.springframework.ide.vscode.boot.java.autowired.AutowiredHoverProvider;
import org.springframework.ide.vscode.boot.java.conditionals.ConditionalsLiveHoverProvider;
import org.springframework.ide.vscode.boot.java.data.DataRepositoryCompletionProcessor;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaCodeLensEngine;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaCompletionEngine;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaDocumentHighlightEngine;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaDocumentSymbolHandler;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaHoverProvider;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaReconcileEngine;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaReferencesHandler;
import org.springframework.ide.vscode.boot.java.handlers.BootJavaWorkspaceSymbolHandler;
import org.springframework.ide.vscode.boot.java.handlers.CodeLensProvider;
import org.springframework.ide.vscode.boot.java.handlers.CompletionProvider;
import org.springframework.ide.vscode.boot.java.handlers.HighlightProvider;
import org.springframework.ide.vscode.boot.java.handlers.HoverProvider;
import org.springframework.ide.vscode.boot.java.handlers.ReferenceProvider;
import org.springframework.ide.vscode.boot.java.links.SourceLinks;
import org.springframework.ide.vscode.boot.java.livehover.ActiveProfilesProvider;
import org.springframework.ide.vscode.boot.java.livehover.BeanInjectedIntoHoverProvider;
import org.springframework.ide.vscode.boot.java.livehover.ComponentInjectionsHoverProvider;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessCommandHandler;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnectorLocal;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnectorRemote;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessConnectorService;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessLiveDataProvider;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessLiveHoverUpdater;
import org.springframework.ide.vscode.boot.java.livehover.v2.SpringProcessTracker;
import org.springframework.ide.vscode.boot.java.requestmapping.LiveAppURLSymbolProvider;
import org.springframework.ide.vscode.boot.java.requestmapping.RequestMappingHoverProvider;
import org.springframework.ide.vscode.boot.java.requestmapping.WebfluxHandlerCodeLensProvider;
import org.springframework.ide.vscode.boot.java.requestmapping.WebfluxRouteHighlightProdivder;
import org.springframework.ide.vscode.boot.java.scope.ScopeCompletionProcessor;
import org.springframework.ide.vscode.boot.java.snippets.JavaSnippet;
import org.springframework.ide.vscode.boot.java.snippets.JavaSnippetContext;
import org.springframework.ide.vscode.boot.java.snippets.JavaSnippetManager;
import org.springframework.ide.vscode.boot.java.utils.CompilationUnitCache;
import org.springframework.ide.vscode.boot.java.utils.SpringLiveChangeDetectionWatchdog;
import org.springframework.ide.vscode.boot.java.utils.SymbolCache;
import org.springframework.ide.vscode.boot.java.value.ValueCompletionProcessor;
import org.springframework.ide.vscode.boot.java.value.ValueHoverProvider;
import org.springframework.ide.vscode.boot.java.value.ValuePropertyReferencesProvider;
import org.springframework.ide.vscode.boot.metadata.ProjectBasedPropertyIndexProvider;
import org.springframework.ide.vscode.boot.metadata.SpringPropertyIndexProvider;
import org.springframework.ide.vscode.commons.languageserver.completion.ICompletionEngine;
import org.springframework.ide.vscode.commons.languageserver.composable.LanguageServerComponents;
import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder;
import org.springframework.ide.vscode.commons.languageserver.java.ProjectObserver;
import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine;
import org.springframework.ide.vscode.commons.languageserver.util.CodeLensHandler;
import org.springframework.ide.vscode.commons.languageserver.util.DocumentHighlightHandler;
import org.springframework.ide.vscode.commons.languageserver.util.HoverHandler;
import org.springframework.ide.vscode.commons.languageserver.util.LspClient;
import org.springframework.ide.vscode.commons.languageserver.util.ReferencesHandler;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleWorkspaceService;
import org.springframework.ide.vscode.commons.util.text.LanguageId;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* Language Server for Spring Boot Application Properties files
*
* @author Martin Lippert
*/
public class BootJavaLanguageServerComponents implements LanguageServerComponents {
//TODO: This class is supposed to go away. It is basically a 'collection of beans'.
// I.e. all the 'components' in here should really become separate beans.
// So... moving forward...
// Do not add more components here. You should instead just make your new
// components into separate beans.
private static final Logger log = LoggerFactory.getLogger(BootJavaLanguageServerComponents.class);
public static final Set<LanguageId> LANGUAGES = ImmutableSet.of(LanguageId.JAVA, LanguageId.CLASS);
private final SimpleLanguageServer server;
private final BootLanguageServerParams serverParams;
private final SpringPropertyIndexProvider propertyIndexProvider;
private final ProjectBasedPropertyIndexProvider adHocPropertyIndexProvider;
private final SpringProcessConnectorService liveDataService;
private final SpringLiveChangeDetectionWatchdog liveChangeDetectionWatchdog;
private final ProjectObserver projectObserver;
private final CompilationUnitCache cuCache;
private JavaProjectFinder projectFinder;
private BootJavaHoverProvider hoverProvider;
private CodeLensHandler codeLensHandler;
private DocumentHighlightHandler highlightsEngine;
private BootJavaReconcileEngine reconcileEngine;
private SpringProcessTracker liveProcessTracker;
public BootJavaLanguageServerComponents(
SimpleLanguageServer server,
BootLanguageServerParams serverParams,
SourceLinks sourceLinks,
CompilationUnitCache cuCache,
ProjectBasedPropertyIndexProvider adHocIndexProvider,
SymbolCache symbolCache,
SpringProcessLiveDataProvider liveDataProvider,
BootJavaConfig config,
SpringSymbolIndex indexer
) {
this.server = server;
this.serverParams = serverParams;
projectFinder = serverParams.projectFinder;
projectObserver = serverParams.projectObserver;
this.cuCache = cuCache;
propertyIndexProvider = serverParams.indexProvider;
this.adHocPropertyIndexProvider = adHocIndexProvider;
SimpleWorkspaceService workspaceService = server.getWorkspaceService();
SimpleTextDocumentService documents = server.getTextDocumentService();
ReferencesHandler referencesHandler = createReferenceHandler(server, projectFinder);
documents.onReferences(referencesHandler);
// live data component wiring
// central live data components (to coordinate live data flow)
liveDataService = new SpringProcessConnectorService(server, liveDataProvider);
// connect the live data provider with the hovers (for data extraction and live updates)
hoverProvider = createHoverHandler(projectFinder, sourceLinks, liveDataProvider);
new SpringProcessLiveHoverUpdater(server, hoverProvider, projectFinder, liveDataProvider);
// deal with locally running processes and their connections
SpringProcessConnectorLocal liveDataLocalProcessConnector = new SpringProcessConnectorLocal(liveDataService, projectObserver);
// deal with configured remote connections
SpringProcessConnectorRemote liveDataRemoteProcessConnector = new SpringProcessConnectorRemote(server, liveDataService);
// create and handle commands
new SpringProcessCommandHandler(server, liveDataService, liveDataLocalProcessConnector, liveDataRemoteProcessConnector);
// track locally running processes and automatically connect to them if configured to do so
liveProcessTracker = new SpringProcessTracker(liveDataLocalProcessConnector, Duration.ofMillis(config.getLiveInformationAutomaticTrackingDelay()));
documents.onDocumentSymbol(new BootJavaDocumentSymbolHandler(indexer));
workspaceService.onWorkspaceSymbol(new BootJavaWorkspaceSymbolHandler(indexer,
new LiveAppURLSymbolProvider(liveDataProvider)));
liveChangeDetectionWatchdog = new SpringLiveChangeDetectionWatchdog(
this,
server,
serverParams.projectObserver,
projectFinder,
Duration.ofSeconds(5),
sourceLinks);
codeLensHandler = createCodeLensEngine(indexer);
documents.onCodeLens(codeLensHandler);
highlightsEngine = createDocumentHighlightEngine(indexer);
documents.onDocumentHighlight(highlightsEngine);
reconcileEngine = new BootJavaReconcileEngine(cuCache, projectFinder);
config.addListener(ignore -> {
log.info("update live process tracker settings - start");
// live information automatic process tracking
liveProcessTracker.setDelay(config.getLiveInformationAutomaticTrackingDelay());
liveProcessTracker.setTrackingEnabled(config.isLiveInformationAutomaticTrackingEnabled());
// live information data fetch params
liveDataService.setMaxRetryCount(config.getLiveInformationFetchDataMaxRetryCount());
liveDataService.setRetryDelayInSeconds(config.getLiveInformationFetchDataRetryDelayInSeconds());
// live change detection watchdog
if (config.isChangeDetectionEnabled()) {
liveChangeDetectionWatchdog.enableHighlights();
}
else {
liveChangeDetectionWatchdog.disableHighlights();
}
reconcileEngine.setSpelExpressionSyntaxValidationEnabled(config.isSpelExpressionValidationEnabled());
log.info("update live process tracker settings - done");
});
server.doOnInitialized(this::initialized);
server.onShutdown(this::shutdown);
}
public SimpleLanguageServer getServer() {
return server;
}
@Override
public Optional<ICompletionEngine> getCompletionEngine() {
return Optional.of(createCompletionEngine(projectFinder, propertyIndexProvider, adHocPropertyIndexProvider));
}
@Override
public HoverHandler getHoverProvider() {
return hoverProvider;
}
public CodeLensHandler getCodeLensHandler() {
return codeLensHandler;
}
public DocumentHighlightHandler getDocumentHighlightHandler() {
return highlightsEngine;
}
@Override
public Optional<IReconcileEngine> getReconcileEngine() {
return Optional.of(reconcileEngine);
}
private void initialized() {
this.liveProcessTracker.start();
this.liveChangeDetectionWatchdog.start();
}
private void shutdown() {
this.liveProcessTracker.stop();
this.liveChangeDetectionWatchdog.shutdown();
this.cuCache.dispose();
}
protected ICompletionEngine createCompletionEngine(
JavaProjectFinder javaProjectFinder,
SpringPropertyIndexProvider indexProvider,
ProjectBasedPropertyIndexProvider adHocIndexProvider) {
Map<String, CompletionProvider> providers = new HashMap<>();
providers.put(org.springframework.ide.vscode.boot.java.scope.Constants.SPRING_SCOPE,
new ScopeCompletionProcessor());
providers.put(org.springframework.ide.vscode.boot.java.value.Constants.SPRING_VALUE,
new ValueCompletionProcessor(javaProjectFinder, indexProvider, adHocIndexProvider));
providers.put(Annotations.REPOSITORY, new DataRepositoryCompletionProcessor());
JavaSnippetManager snippetManager = getSnippets();
return new BootJavaCompletionEngine(this, providers, snippetManager);
}
protected JavaSnippetManager getSnippets() {
JavaSnippetManager snippetManager = new JavaSnippetManager(server::createSnippetBuilder);
// PT 160529904: Eclipse templates are duplicated, due to templates in Eclipse also being contributed by
// STS3 bundle. Therefore do not include templates if client is Eclipse
// TODO: REMOVE this check once STS3 is no longer supported
if (LspClient.currentClient() != LspClient.Client.ECLIPSE) {
snippetManager.add(
new JavaSnippet("RequestMapping method", JavaSnippetContext.BOOT_MEMBERS, CompletionItemKind.Method,
ImmutableList.of("org.springframework.web.bind.annotation.RequestMapping",
"org.springframework.web.bind.annotation.RequestMethod",
"org.springframework.web.bind.annotation.RequestParam"),
"@RequestMapping(value=\"${path}\", method=RequestMethod.${GET})\n"
+ "public ${SomeData} ${requestMethodName}(@RequestParam ${String} ${param}) {\n"
+ " return new ${SomeData}(${cursor});\n" + "}\n"));
snippetManager
.add(new JavaSnippet("GetMapping method", JavaSnippetContext.BOOT_MEMBERS, CompletionItemKind.Method,
ImmutableList.of("org.springframework.web.bind.annotation.GetMapping",
"org.springframework.web.bind.annotation.RequestParam"),
"@GetMapping(value=\"${path}\")\n"
+ "public ${SomeData} ${getMethodName}(@RequestParam ${String} ${param}) {\n"
+ " return new ${SomeData}(${cursor});\n" + "}\n"));
snippetManager.add(new JavaSnippet("PostMapping method", JavaSnippetContext.BOOT_MEMBERS,
CompletionItemKind.Method,
ImmutableList.of("org.springframework.web.bind.annotation.PostMapping",
"org.springframework.web.bind.annotation.RequestBody"),
"@PostMapping(value=\"${path}\")\n"
+ "public ${SomeEnityData} ${postMethodName}(@RequestBody ${SomeEnityData} ${entity}) {\n"
+ " //TODO: process POST request\n" + " ${cursor}\n" + " return ${entity};\n" + "}\n"));
snippetManager.add(new JavaSnippet("PutMapping method", JavaSnippetContext.BOOT_MEMBERS,
CompletionItemKind.Method,
ImmutableList.of("org.springframework.web.bind.annotation.PutMapping",
"org.springframework.web.bind.annotation.RequestBody",
"org.springframework.web.bind.annotation.PathVariable"),
"@PutMapping(value=\"${path}/{${id}}\")\n"
+ "public ${SomeEnityData} ${putMethodName}(@PathVariable ${pvt:String} ${id}, @RequestBody ${SomeEnityData} ${entity}) {\n"
+ " //TODO: process PUT request\n" + " ${cursor}\n" + " return ${entity};\n" + "}"));
}
return snippetManager;
}
protected BootJavaHoverProvider createHoverHandler(JavaProjectFinder javaProjectFinder, SourceLinks sourceLinks,
SpringProcessLiveDataProvider liveDataProvider) {
AnnotationHierarchyAwareLookup<HoverProvider> providers = new AnnotationHierarchyAwareLookup<>();
ValueHoverProvider valueHoverProvider = new ValueHoverProvider();
RequestMappingHoverProvider requestMappingHoverProvider = new RequestMappingHoverProvider();
AutowiredHoverProvider autowiredHoverProvider = new AutowiredHoverProvider(sourceLinks);
ComponentInjectionsHoverProvider componentInjectionsHoverProvider = new ComponentInjectionsHoverProvider(sourceLinks);
BeanInjectedIntoHoverProvider beanInjectedIntoHoverProvider = new BeanInjectedIntoHoverProvider(sourceLinks);
ConditionalsLiveHoverProvider conditionalsLiveHoverProvider = new ConditionalsLiveHoverProvider();
providers.put(org.springframework.ide.vscode.boot.java.value.Constants.SPRING_VALUE, valueHoverProvider);
providers.put(Annotations.SPRING_REQUEST_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.SPRING_GET_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.SPRING_POST_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.SPRING_PUT_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.SPRING_DELETE_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.SPRING_PATCH_MAPPING, requestMappingHoverProvider);
providers.put(Annotations.PROFILE, new ActiveProfilesProvider());
providers.put(Annotations.AUTOWIRED, autowiredHoverProvider);
providers.put(Annotations.INJECT, autowiredHoverProvider);
providers.put(Annotations.COMPONENT, componentInjectionsHoverProvider);
providers.put(Annotations.BEAN, beanInjectedIntoHoverProvider);
providers.put(Annotations.CONDITIONAL, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_BEAN, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_MISSING_BEAN, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_PROPERTY, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_RESOURCE, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_CLASS, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_MISSING_CLASS, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_CLOUD_PLATFORM, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_WEB_APPLICATION, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_NOT_WEB_APPLICATION, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_ENABLED_INFO_CONTRIBUTOR, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_ENABLED_RESOURCE_CHAIN, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_ENABLED_ENDPOINT, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_ENABLED_HEALTH_INDICATOR, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_EXPRESSION, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_JAVA, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_JNDI, conditionalsLiveHoverProvider);
providers.put(Annotations.CONDITIONAL_ON_SINGLE_CANDIDATE, conditionalsLiveHoverProvider);
return new BootJavaHoverProvider(this, javaProjectFinder, providers, liveDataProvider);
}
protected ReferencesHandler createReferenceHandler(SimpleLanguageServer server, JavaProjectFinder projectFinder) {
Map<String, ReferenceProvider> providers = new HashMap<>();
providers.put(org.springframework.ide.vscode.boot.java.value.Constants.SPRING_VALUE,
new ValuePropertyReferencesProvider(server));
return new BootJavaReferencesHandler(this, projectFinder, providers);
}
protected BootJavaCodeLensEngine createCodeLensEngine(SpringSymbolIndex index) {
Collection<CodeLensProvider> codeLensProvider = new ArrayList<>();
codeLensProvider.add(new WebfluxHandlerCodeLensProvider(index));
return new BootJavaCodeLensEngine(this, codeLensProvider);
}
protected BootJavaDocumentHighlightEngine createDocumentHighlightEngine(SpringSymbolIndex indexer) {
Collection<HighlightProvider> highlightProvider = new ArrayList<>();
highlightProvider.add(new WebfluxRouteHighlightProdivder(indexer));
return new BootJavaDocumentHighlightEngine(this, highlightProvider);
}
public ProjectObserver getProjectObserver() {
return projectObserver;
}
public JavaProjectFinder getProjectFinder() {
return projectFinder;
}
public SpringPropertyIndexProvider getSpringPropertyIndexProvider() {
return propertyIndexProvider;
}
public CompilationUnitCache getCompilationUnitCache() {
return cuCache;
}
public SimpleTextDocumentService getTextDocumentService() {
return server.getTextDocumentService();
}
public BootLanguageServerParams getServerParams() {
return this.serverParams;
}
@Override
public Set<LanguageId> getInterestingLanguages() {
return LANGUAGES;
}
}
|
package com.x.processplatform.service.processing.processor.manual;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.script.Bindings;
import javax.script.ScriptContext;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.organization.EmpowerLog;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.tools.DateTools;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.NumberTools;
import com.x.base.core.project.utils.time.WorkTime;
import com.x.processplatform.core.entity.content.Read;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.TaskCompleted;
import com.x.processplatform.core.entity.content.Work;
import com.x.processplatform.core.entity.content.WorkLog;
import com.x.processplatform.core.entity.element.ActivityType;
import com.x.processplatform.core.entity.element.Manual;
import com.x.processplatform.core.entity.element.Route;
import com.x.processplatform.core.entity.element.util.WorkLogTree;
import com.x.processplatform.core.entity.element.util.WorkLogTree.Node;
import com.x.processplatform.core.entity.log.Signal;
import com.x.processplatform.service.processing.Business;
import com.x.processplatform.service.processing.processor.AeiObjects;
/**
* @author Zhou Rui
*/
public class ManualProcessor extends AbstractManualProcessor {
private static Logger logger = LoggerFactory.getLogger(ManualProcessor.class);
public ManualProcessor(EntityManagerContainer entityManagerContainer) throws Exception {
super(entityManagerContainer);
}
@Override
protected Work arriving(AeiObjects aeiObjects, Manual manual) throws Exception {
// ProcessingSignal
aeiObjects.getProcessingAttributes().push(Signal.manualArrive(aeiObjects.getWork().getActivityToken(), manual));
// manual
List<String> identities = calculateTaskIdentities(aeiObjects, manual);
Work merge = this.arrivingMergeSameJob(aeiObjects, manual, identities);
if (null != merge) {
return merge;
}
this.arrivingPassSame(aeiObjects, identities);
aeiObjects.getWork().setManualTaskIdentityList(new ArrayList<>(identities));
return aeiObjects.getWork();
}
private Work arrivingMergeSameJob(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
if (!BooleanUtils.isTrue(manual.getManualMergeSameJobActivity())) {
return null;
}
List<String> exists = this.arriving_sameJobActivityExistIdentities(aeiObjects, manual);
if (ListTools.isNotEmpty(exists)) {
Work other = aeiObjects.getWorks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getJob(), o.getJob())
&& StringUtils.equals(aeiObjects.getWork().getActivity(), o.getActivity())
&& (!Objects.equals(aeiObjects.getWork(), o));
}).findFirst().orElse(null);
if (null != other) {
identities.removeAll(exists);
if (ListTools.isEmpty(identities)) {
this.mergeTaskCompleted(aeiObjects, aeiObjects.getWork(), other);
this.mergeRead(aeiObjects, aeiObjects.getWork(), other);
this.mergeReadCompleted(aeiObjects, aeiObjects.getWork(), other);
this.mergeReview(aeiObjects, aeiObjects.getWork(), other);
this.mergeAttachment(aeiObjects, aeiObjects.getWork(), other);
this.mergeWorkLog(aeiObjects, aeiObjects.getWork(), other);
if (ListTools.size(aeiObjects.getWork().getSplitTokenList()) > ListTools
.size(other.getSplitTokenList())) {
other.setSplitTokenList(aeiObjects.getWork().getSplitTokenList());
other.setSplitToken(aeiObjects.getWork().getSplitToken());
other.setSplitValue(aeiObjects.getWork().getSplitValue());
other.setSplitting(true);
}
aeiObjects.getUpdateWorks().add(other);
aeiObjects.getDeleteWorks().add(aeiObjects.getWork());
return other;
}
}
}
return null;
}
private void arrivingPassSame(AeiObjects aeiObjects, List<String> identities) throws Exception {
// passSameTarget
Route route = aeiObjects.getRoutes().stream().filter(o -> BooleanUtils.isTrue(o.getPassSameTarget()))
.findFirst().orElse(null);
// passSameTarget,ArriveWorkLog,
if ((null != route) && ((null != aeiObjects.getArriveWorkLog(aeiObjects.getWork())))
&& (!aeiObjects.getProcessingAttributes().ifForceJoinAtArrive())) {
WorkLog workLog = findPassSameTargetWorkLog(aeiObjects);
logger.debug("pass same target work:{}, workLog:{}.", aeiObjects.getWork(), workLog);
if (null == workLog) {
return;
}
for (TaskCompleted o : aeiObjects.getJoinInquireTaskCompleteds()) {
if (StringUtils.equals(o.getActivityToken(), workLog.getArrivedActivityToken())) {
List<String> values = ListUtils.intersection(identities,
aeiObjects.business().organization().identity().listWithPerson(o.getPerson()));
if (!values.isEmpty()) {
TaskCompleted obj = new TaskCompleted(aeiObjects.getWork(), route, o);
obj.setIdentity(values.get(0));
obj.setUnit(aeiObjects.business().organization().unit().getWithIdentity(obj.getIdentity()));
obj.setProcessingType(TaskCompleted.PROCESSINGTYPE_SAMETARGET);
obj.setRouteName(route.getName());
Date now = new Date();
obj.setStartTime(now);
obj.setStartTimeMonth(DateTools.format(now, DateTools.format_yyyyMM));
obj.setCompletedTime(now);
obj.setCompletedTimeMonth(DateTools.format(now, DateTools.format_yyyyMM));
obj.setDuration(0L);
obj.setExpired(false);
obj.setExpireTime(null);
obj.setTask(null);
obj.setLatest(true);
aeiObjects.getCreateTaskCompleteds().add(obj);
}
}
}
}
}
private List<String> calculateTaskIdentities(AeiObjects aeiObjects, Manual manual) throws Exception {
TaskIdentities taskIdentities = new TaskIdentities();
if (!aeiObjects.getWork().getProperties().getManualForceTaskIdentityList().isEmpty()) {
List<String> identities = new ArrayList<>();
identities.addAll(aeiObjects.getWork().getProperties().getManualForceTaskIdentityList());
identities = aeiObjects.business().organization().identity().list(identities);
if (ListTools.isNotEmpty(identities)) {
taskIdentities.addIdentities(identities);
}
}
if (taskIdentities.isEmpty()) {
Route route = aeiObjects.business().element().get(aeiObjects.getWork().getDestinationRoute(), Route.class);
if ((null != route) && (StringUtils.equals(route.getType(), Route.TYPE_BACK))) {
List<String> identities = new ArrayList<>();
List<WorkLog> workLogs = new ArrayList<>();
workLogs.addAll(aeiObjects.getUpdateWorkLogs());
workLogs.addAll(aeiObjects.getCreateWorkLogs());
for (WorkLog o : aeiObjects.getWorkLogs()) {
if (!workLogs.contains(o)) {
workLogs.add(o);
}
}
WorkLogTree tree = new WorkLogTree(workLogs);
Node node = tree.location(aeiObjects.getWork());
if (null != node) {
for (Node n : tree.up(node)) {
if (StringUtils.equals(manual.getId(), n.getWorkLog().getFromActivity())) {
for (TaskCompleted t : aeiObjects.getTaskCompleteds()) {
if (StringUtils.equals(n.getWorkLog().getFromActivityToken(), t.getActivityToken())
&& BooleanUtils.isTrue(t.getJoinInquire())) {
identities.add(t.getIdentity());
}
}
break;
}
}
identities = aeiObjects.business().organization().identity().list(identities);
if (ListTools.isNotEmpty(identities)) {
taskIdentities.addIdentities(identities);
}
}
}
}
if (taskIdentities.isEmpty()) {
taskIdentities = TranslateTaskIdentityTools.translate(aeiObjects, manual);
this.ifTaskIdentitiesEmptyForceToCreatorOrMaintenance(aeiObjects, manual, taskIdentities);
this.writeToEmpowerMap(aeiObjects, taskIdentities);
}
return taskIdentities.identities();
}
// ,, maintenanceIdentity
private void ifTaskIdentitiesEmptyForceToCreatorOrMaintenance(AeiObjects aeiObjects, Manual manual,
TaskIdentities taskIdentities) throws Exception {
if (taskIdentities.isEmpty()) {
String identity = aeiObjects.business().organization().identity()
.get(aeiObjects.getWork().getCreatorIdentity());
if (StringUtils.isNotEmpty(identity)) {
logger.info("{}[{}], :{}, id:{}, :{}.", aeiObjects.getProcess().getName(),
manual.getName(), aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(), identity);
taskIdentities.addIdentity(identity);
} else {
identity = aeiObjects.business().organization().identity()
.get(Config.processPlatform().getMaintenanceIdentity());
if (StringUtils.isNotEmpty(identity)) {
logger.info("{}[{}], , :{}, id:{}, :{}.",
aeiObjects.getProcess().getName(), manual.getName(), aeiObjects.getWork().getTitle(),
aeiObjects.getWork().getId(), identity);
taskIdentities.addIdentity(identity);
} else {
throw new ExceptionExpectedEmpty(aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(),
aeiObjects.getActivity().getName(), aeiObjects.getActivity().getId());
}
}
}
}
// ,surfaceworkThroughManual=false ,.
private void writeToEmpowerMap(AeiObjects aeiObjects, TaskIdentities taskIdentities) throws Exception {
// EmpowerMap
aeiObjects.getWork().getProperties().setManualEmpowerMap(new LinkedHashMap<String, String>());
if (!(StringUtils.equals(aeiObjects.getWork().getWorkCreateType(), Work.WORKCREATETYPE_SURFACE)
&& BooleanUtils.isFalse(aeiObjects.getWork().getWorkThroughManual()))) {
List<String> values = taskIdentities.identities();
values = ListUtils.subtract(values, aeiObjects.getProcessingAttributes().getIgnoreEmpowerIdentityList());
taskIdentities.empower(aeiObjects.business().organization().empower().listWithIdentityObject(
aeiObjects.getWork().getApplication(), aeiObjects.getProcess().getEdition(),
aeiObjects.getWork().getProcess(), aeiObjects.getWork().getId(), values));
for (TaskIdentity taskIdentity : taskIdentities) {
if (StringUtils.isNotEmpty(taskIdentity.getFromIdentity())) {
aeiObjects.getWork().getProperties().getManualEmpowerMap().put(taskIdentity.getIdentity(),
taskIdentity.getFromIdentity());
}
}
}
}
private WorkLog findPassSameTargetWorkLog(AeiObjects aeiObjects) throws Exception {
WorkLogTree tree = new WorkLogTree(aeiObjects.getWorkLogs());
List<WorkLog> parents = tree.parents(aeiObjects.getArriveWorkLog(aeiObjects.getWork()));
logger.debug("pass same target rollback parents:{}.", parents);
WorkLog workLog = null;
for (WorkLog o : parents) {
if (Objects.equals(ActivityType.manual, o.getArrivedActivityType())) {
workLog = o;
break;
} else if (Objects.equals(ActivityType.choice, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.agent, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.invoke, o.getArrivedActivityType())) {
continue;
} else if (Objects.equals(ActivityType.service, o.getArrivedActivityType())) {
continue;
} else {
break;
}
}
logger.debug("pass same target find workLog:{}.", workLog);
return workLog;
}
@Override
protected void arrivingCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
@Override
protected List<Work> executing(AeiObjects aeiObjects, Manual manual) throws Exception {
List<Work> results = new ArrayList<>();
boolean passThrough = false;
List<String> identities = aeiObjects.business().organization().identity()
.list(aeiObjects.getWork().getManualTaskIdentityList());
if (identities.isEmpty()) {
identities = calculateTaskIdentities(aeiObjects, manual);
logger.info(",,:{}, id:{}, :{}.", aeiObjects.getWork().getTitle(),
aeiObjects.getWork().getId(), identities);
// identitis.remove()
aeiObjects.getWork().setManualTaskIdentityList(new ArrayList<>(identities));
}
// ProcessingSignal
aeiObjects.getProcessingAttributes().push(Signal.manualExecute(aeiObjects.getWork().getActivityToken(), manual,
Objects.toString(manual.getManualMode(), ""), identities));
switch (manual.getManualMode()) {
case single:
passThrough = this.single(aeiObjects, manual, identities);
break;
case parallel:
passThrough = this.parallel(aeiObjects, manual, identities);
break;
case queue:
passThrough = this.queue(aeiObjects, manual, identities);
break;
case grab:
passThrough = this.single(aeiObjects, manual, identities);
break;
default:
throw new ExceptionManualModeError(manual.getId());
}
if (passThrough) {
results.add(aeiObjects.getWork());
}
return results;
}
@Override
protected void executingCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
@Override
protected List<Route> inquiring(AeiObjects aeiObjects, Manual manual) throws Exception {
// ProcessingSignal
aeiObjects.getProcessingAttributes()
.push(Signal.manualInquire(aeiObjects.getWork().getActivityToken(), manual));
List<Route> results = new ArrayList<>();
if (aeiObjects.getRoutes().size() == 1) {
results.add(aeiObjects.getRoutes().get(0));
} else if (aeiObjects.getRoutes().size() > 1) {
List<TaskCompleted> taskCompletedList = aeiObjects.getJoinInquireTaskCompleteds().stream()
.filter(o -> StringUtils.equals(o.getActivityToken(), aeiObjects.getWork().getActivityToken())
&& aeiObjects.getWork().getManualTaskIdentityList().contains(o.getIdentity()))
.collect(Collectors.toList());
String name = this.choiceRouteName(taskCompletedList, aeiObjects.getRoutes());
for (Route o : aeiObjects.getRoutes()) {
if (o.getName().equalsIgnoreCase(name)) {
results.add(o);
break;
}
}
}
if (!results.isEmpty()) {
aeiObjects.getWork().getProperties().setManualForceTaskIdentityList(new ArrayList<String>());
}
return results;
}
private String choiceRouteName(List<TaskCompleted> list, List<Route> routes) throws Exception {
String result = "";
List<String> names = new ArrayList<>();
ListTools.trim(list, false, false).stream().forEach(o -> names.add(o.getRouteName()));
Route soleRoute = routes.stream().filter(o -> BooleanUtils.isTrue(o.getSole())).findFirst().orElse(null);
if ((null != soleRoute) && names.contains(soleRoute.getName())) {
result = soleRoute.getName();
} else {
result = maxCountOrLatest(list);
}
if (StringUtils.isEmpty(result)) {
throw new ExceptionChoiceRouteNameError(
ListTools.extractProperty(list, JpaObject.id_FIELDNAME, String.class, false, false));
}
return result;
}
private String maxCountOrLatest(List<TaskCompleted> list) {
Map<String, List<TaskCompleted>> map = list.stream()
.collect(Collectors.groupingBy(TaskCompleted::getRouteName));
Optional<Entry<String, List<TaskCompleted>>> optional = map.entrySet().stream().sorted((o1, o2) -> {
int c = o2.getValue().size() - o1.getValue().size();
if (c == 0) {
Date d1 = o1.getValue().stream().sorted(Comparator.comparing(TaskCompleted::getCreateTime).reversed())
.findFirst().get().getCreateTime();
Date d2 = o2.getValue().stream().sorted(Comparator.comparing(TaskCompleted::getCreateTime).reversed())
.findFirst().get().getCreateTime();
return ObjectUtils.compare(d2, d1);
} else {
return c;
}
}).findFirst();
return optional.isPresent() ? optional.get().getKey() : null;
}
private boolean single(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
Long count = aeiObjects.getJoinInquireTaskCompleteds().stream().filter(o -> {
if (StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (identities.contains(o.getIdentity()))) {
return true;
} else {
return false;
}
}).count();
if (count > 0) {
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getId(), o.getWork());
}).forEach(o -> {
if (BooleanUtils.isTrue(manual.getManualUncompletedTaskToRead())) {
aeiObjects.getCreateReads()
.add(new Read(aeiObjects.getWork(), o.getIdentity(), o.getUnit(), o.getPerson()));
}
aeiObjects.deleteTask(o);
});
passThrough = true;
} else {
// List
if (ListTools.isEmpty(identities)) {
throw new ExceptionExpectedEmpty(aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(),
manual.getName(), manual.getId());
}
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (!ListTools.contains(identities, o.getIdentity())))
.forEach(aeiObjects::deleteTask);
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (ListTools.contains(identities, o.getIdentity())))
.forEach(o -> identities.remove(o.getIdentity()));
if (!identities.isEmpty()) {
for (String identity : identities) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
}
return passThrough;
}
private boolean parallel(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
List<TaskCompleted> taskCompleteds = this.listJoinInquireTaskCompleted(aeiObjects, identities);
// ,.soleDirect
Route soleRoute = aeiObjects.getRoutes().stream()
.filter(r -> BooleanUtils.isTrue(r.getSole()) && BooleanUtils.isTrue(r.getSoleDirect())).findFirst()
.orElse(null);
if (null != soleRoute) {
TaskCompleted soleTaskCompleted = taskCompleteds.stream()
.filter(t -> BooleanUtils.isTrue(t.getJoinInquire())
&& StringUtils.equals(t.getRouteName(), soleRoute.getName()))
.findFirst().orElse(null);
if (null != soleTaskCompleted) {
this.parallelSoleTaskCompleted(aeiObjects);
return true;
}
}
aeiObjects.getJoinInquireTaskCompleteds().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken());
}).forEach(o -> identities.remove(o.getIdentity()));
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& (!ListTools.contains(identities, o.getIdentity()));
}).forEach(aeiObjects::deleteTask);
if (identities.isEmpty()) {
passThrough = true;
} else {
passThrough = false;
aeiObjects.getTasks().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken()))
.forEach(o -> identities.remove(o.getIdentity()));
if (!identities.isEmpty()) {
for (String identity : identities) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
}
return passThrough;
}
private void parallelSoleTaskCompleted(AeiObjects aeiObjects) throws Exception {
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken());
}).forEach(aeiObjects::deleteTask);
}
private boolean queue(AeiObjects aeiObjects, Manual manual, List<String> identities) throws Exception {
boolean passThrough = false;
List<TaskCompleted> taskCompleteds = this.listJoinInquireTaskCompleted(aeiObjects, identities);
Route soleRoute = aeiObjects.getRoutes().stream().filter(r -> BooleanUtils.isTrue(r.getSole())).findFirst()
.orElse(null);
if (null != soleRoute) {
TaskCompleted soleTaskCompleted = taskCompleteds.stream()
.filter(t -> BooleanUtils.isTrue(t.getJoinInquire())
&& StringUtils.equals(t.getRouteName(), soleRoute.getName()))
.findFirst().orElse(null);
if (null != soleTaskCompleted) {
return true;
}
}
for (TaskCompleted o : taskCompleteds) {
identities.remove(o.getIdentity());
}
if (identities.isEmpty()) {
passThrough = true;
} else {
passThrough = false;
String identity = identities.get(0);
boolean find = false;
for (Task t : aeiObjects.getTasks()) {
if (StringUtils.equals(aeiObjects.getWork().getActivityToken(), t.getActivityToken())) {
if (!StringUtils.equals(t.getIdentity(), identity)) {
aeiObjects.deleteTask(t);
} else {
find = true;
}
}
}
if (!find) {
aeiObjects.createTask(this.createTask(aeiObjects, manual, identity));
}
}
return passThrough;
}
// , reset,retract,appendTask
private List<TaskCompleted> listJoinInquireTaskCompleted(AeiObjects aeiObjects, List<String> identities)
throws Exception {
return aeiObjects.getJoinInquireTaskCompleteds().stream()
.filter(o -> StringUtils.equals(aeiObjects.getWork().getActivityToken(), o.getActivityToken())
&& identities.contains(o.getIdentity()) && BooleanUtils.isTrue(o.getJoinInquire()))
.collect(Collectors.toList());
}
@Override
protected void inquiringCommitted(AeiObjects aeiObjects, Manual manual) throws Exception {
// nothing
}
private void calculateExpire(AeiObjects aeiObjects, Manual manual, Task task) throws Exception {
if (null != manual.getTaskExpireType()) {
switch (manual.getTaskExpireType()) {
case never:
this.expireNever(task);
break;
case appoint:
this.expireAppoint(manual, task);
break;
case script:
this.expireScript(aeiObjects, manual, task);
break;
default:
break;
}
}
// work
if (null != aeiObjects.getWork().getExpireTime()) {
if (null == task.getExpireTime()) {
task.setExpireTime(aeiObjects.getWork().getExpireTime());
} else {
if (task.getExpireTime().after(aeiObjects.getWork().getExpireTime())) {
task.setExpireTime(aeiObjects.getWork().getExpireTime());
}
}
}
if (null != task.getExpireTime()) {
task.setUrgeTime(DateUtils.addHours(task.getExpireTime(), -2));
} else {
task.setExpired(false);
task.setUrgeTime(null);
task.setUrged(false);
}
}
private void expireNever(Task task) {
task.setExpireTime(null);
}
private void expireAppoint(Manual manual, Task task) throws Exception {
if (BooleanUtils.isTrue(manual.getTaskExpireWorkTime())) {
this.expireAppointWorkTime(task, manual);
} else {
this.expireAppointNaturalDay(task, manual);
}
}
private void expireAppointWorkTime(Task task, Manual manual) throws Exception {
Integer m = 0;
WorkTime wt = new WorkTime();
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireDay(), 0))) {
m += manual.getTaskExpireDay() * wt.minutesOfWorkDay();
}
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireHour(), 0))) {
m += manual.getTaskExpireHour() * 60;
}
if (m > 0) {
Date expire = wt.forwardMinutes(new Date(), m);
task.setExpireTime(expire);
} else {
task.setExpireTime(null);
}
}
private void expireAppointNaturalDay(Task task, Manual manual) throws Exception {
Integer m = 0;
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireDay(), 0))) {
m += manual.getTaskExpireDay() * 60 * 24;
}
if (BooleanUtils.isTrue(NumberTools.greaterThan(manual.getTaskExpireHour(), 0))) {
m += manual.getTaskExpireHour() * 60;
}
if (m > 0) {
Calendar cl = Calendar.getInstance();
cl.add(Calendar.MINUTE, m);
task.setExpireTime(cl.getTime());
} else {
task.setExpireTime(null);
}
}
private void expireScript(AeiObjects aeiObjects, Manual manual, Task task) throws Exception {
ExpireScriptResult expire = new ExpireScriptResult();
ScriptContext scriptContext = aeiObjects.scriptContext();
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put(ScriptFactory.BINDING_NAME_TASK, task);
bindings.put(ScriptFactory.BINDING_NAME_EXPIRE, expire);
ScriptFactory.initialScriptText().eval(scriptContext);
aeiObjects.business().element()
.getCompiledScript(aeiObjects.getWork().getApplication(), manual, Business.EVENT_MANUALTASKEXPIRE)
.eval(scriptContext);
if (BooleanUtils.isTrue(NumberTools.greaterThan(expire.getWorkHour(), 0))) {
Integer m = 0;
m += expire.getWorkHour() * 60;
if (m > 0) {
WorkTime wt = new WorkTime();
task.setExpireTime(wt.forwardMinutes(new Date(), m));
} else {
task.setExpireTime(null);
}
} else if (BooleanUtils.isTrue(NumberTools.greaterThan(expire.getHour(), 0))) {
Integer m = 0;
m += expire.getHour() * 60;
if (m > 0) {
Calendar cl = Calendar.getInstance();
cl.add(Calendar.MINUTE, m);
task.setExpireTime(cl.getTime());
} else {
task.setExpireTime(null);
}
} else if (null != expire.getDate()) {
task.setExpireTime(expire.getDate());
} else {
task.setExpireTime(null);
}
}
private Task createTask(AeiObjects aeiObjects, Manual manual, String identity) throws Exception {
String fromIdentity = aeiObjects.getWork().getProperties().getManualEmpowerMap().get(identity);
String person = aeiObjects.business().organization().person().getWithIdentity(identity);
String unit = aeiObjects.business().organization().unit().getWithIdentity(identity);
Task task = new Task(aeiObjects.getWork(), identity, person, unit, fromIdentity, new Date(), null,
aeiObjects.getRoutes(), manual.getAllowRapid());
task.setFirst(ListTools.isEmpty(aeiObjects.getJoinInquireTaskCompleteds()));
this.calculateExpire(aeiObjects, manual, task);
if (StringUtils.isNotEmpty(fromIdentity)) {
aeiObjects.business().organization().empowerLog()
.log(this.createEmpowerLog(aeiObjects.getWork(), fromIdentity, identity));
String fromPerson = aeiObjects.business().organization().person().getWithIdentity(fromIdentity);
String fromUnit = aeiObjects.business().organization().unit().getWithIdentity(fromIdentity);
TaskCompleted empowerTaskCompleted = new TaskCompleted(aeiObjects.getWork());
empowerTaskCompleted.setProcessingType(TaskCompleted.PROCESSINGTYPE_EMPOWER);
empowerTaskCompleted.setIdentity(fromIdentity);
empowerTaskCompleted.setUnit(fromUnit);
empowerTaskCompleted.setPerson(fromPerson);
empowerTaskCompleted.setEmpowerToIdentity(identity);
aeiObjects.createTaskCompleted(empowerTaskCompleted);
Read empowerRead = new Read(aeiObjects.getWork(), fromIdentity, fromUnit, fromPerson);
aeiObjects.createRead(empowerRead);
}
return task;
}
private EmpowerLog createEmpowerLog(Work work, String fromIdentity, String toIdentity) {
return new EmpowerLog().setApplication(work.getApplication()).setApplicationAlias(work.getApplicationAlias())
.setApplicationName(work.getApplicationName()).setProcess(work.getProcess())
.setProcessAlias(work.getProcessAlias()).setProcessName(work.getProcessName()).setTitle(work.getTitle())
.setWork(work.getId()).setJob(work.getJob()).setFromIdentity(fromIdentity).setToIdentity(toIdentity)
.setActivity(work.getActivity()).setActivityAlias(work.getActivityAlias())
.setActivityName(work.getActivityName()).setEmpowerTime(new Date());
}
private List<String> arriving_sameJobActivityExistIdentities(AeiObjects aeiObjects, Manual manual)
throws Exception {
List<String> exists = new ArrayList<>();
aeiObjects.getTasks().stream().filter(o -> {
return StringUtils.equals(o.getActivity(), manual.getId())
&& StringUtils.equals(o.getJob(), aeiObjects.getWork().getJob());
}).forEach(o -> exists.add(o.getIdentity()));
return exists;
}
public class ExpireScriptResult {
Integer hour;
Integer workHour;
Date date;
public Integer getHour() {
return hour;
}
public void setHour(Integer hour) {
this.hour = hour;
}
public Integer getWorkHour() {
return workHour;
}
public void setWorkHour(Integer workHour) {
this.workHour = workHour;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void setDate(String str) {
try {
this.date = DateTools.parse(str);
} catch (Exception e) {
logger.error(e);
}
}
}
}
|
package com.opengamma.financial.analytics.model.credit.isda.cdsoption;
import static com.opengamma.engine.value.ValuePropertyNames.CURRENCY;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_CONFIG;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_METHOD;
import static com.opengamma.engine.value.ValuePropertyNames.FUNCTION;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_HAZARD_RATE_CURVE;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_HAZARD_RATE_CURVE_CALCULATION_METHOD;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_SPREAD_CURVE;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_SPREAD_CURVE_SHIFT;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_YIELD_CURVE;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_YIELD_CURVE_CALCULATION_CONFIG;
import static com.opengamma.financial.analytics.model.credit.CreditInstrumentPropertyNamesAndValues.PROPERTY_YIELD_CURVE_CALCULATION_METHOD;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.credit.creditdefaultswapoption.definition.CreditDefaultSwapOptionDefinition;
import com.opengamma.analytics.financial.credit.hazardratecurve.HazardRateCurve;
import com.opengamma.analytics.financial.credit.isdayieldcurve.ISDADateCurve;
import com.opengamma.analytics.math.ParallelArrayBinarySort;
import com.opengamma.analytics.math.curve.NodalObjectsCurve;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.organization.OrganizationSource;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.conversion.CreditDefaultSwapOptionSecurityConverter;
import com.opengamma.financial.analytics.model.YieldCurveFunctionUtils;
import com.opengamma.financial.analytics.model.credit.CreditFunctionUtils;
import com.opengamma.financial.analytics.model.credit.CreditSecurityToIdentifierVisitor;
import com.opengamma.financial.analytics.model.credit.IMMDateGenerator;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityTypes;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.financial.security.option.CreditDefaultSwapOptionSecurity;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.time.Tenor;
public abstract class ISDACreditDefaultSwapOptionFunction extends AbstractFunction.NonCompiledInvoker {
private final String[] _valueRequirements;
public ISDACreditDefaultSwapOptionFunction(final String... valueRequirements) {
ArgumentChecker.notNull(valueRequirements, "value requirements");
_valueRequirements = valueRequirements;
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) throws AsynchronousExecution {
final ZonedDateTime valuationTime = ZonedDateTime.now(executionContext.getValuationClock());
final SecuritySource securitySource = OpenGammaExecutionContext.getSecuritySource(executionContext);
final HolidaySource holidaySource = OpenGammaExecutionContext.getHolidaySource(executionContext);
final RegionSource regionSource = OpenGammaExecutionContext.getRegionSource(executionContext);
final OrganizationSource organizationSource = OpenGammaExecutionContext.getOrganizationSource(executionContext);
final CreditDefaultSwapOptionSecurityConverter converter = new CreditDefaultSwapOptionSecurityConverter(securitySource, holidaySource, regionSource, organizationSource);
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
final CreditDefaultSwapOptionDefinition definition = security.accept(converter);
final Object yieldCurveObject = inputs.getValue(ValueRequirementNames.YIELD_CURVE);
if (yieldCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get yield curve");
}
final Object spreadCurveObject = inputs.getValue(ValueRequirementNames.CREDIT_SPREAD_CURVE);
if (spreadCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get credit spread curve");
}
final Object hazardRateCurveObject = inputs.getValue(ValueRequirementNames.HAZARD_RATE_CURVE);
if (hazardRateCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get hazard rate curve");
}
final ISDADateCurve yieldCurve = (ISDADateCurve) yieldCurveObject;
final double volatility = 0.3; //TODO
final HazardRateCurve hazardRateCurve = (HazardRateCurve) hazardRateCurveObject;
final NodalObjectsCurve<?, ?> spreadCurve = (NodalObjectsCurve<?, ?>) spreadCurveObject;
final Tenor[] tenors = CreditFunctionUtils.getTenors(spreadCurve.getXData());
final Double[] marketSpreadObjects = CreditFunctionUtils.getSpreads(spreadCurve.getYData());
ParallelArrayBinarySort.parallelBinarySort(tenors, marketSpreadObjects);
final int n = tenors.length;
final List<ZonedDateTime> calibrationTimes = new ArrayList<>();
final DoubleArrayList marketSpreads = new DoubleArrayList();
for (int i = 0; i < n; i++) {
final ZonedDateTime nextIMMDate = IMMDateGenerator.getNextIMMDate(valuationTime, tenors[i]).withHour(0).withMinute(0).withSecond(0).withNano(0);
if (nextIMMDate.isAfter(definition.getOptionExerciseDate())) {
calibrationTimes.add(IMMDateGenerator.getNextIMMDate(valuationTime, tenors[i]).withHour(0).withMinute(0).withSecond(0).withNano(0));
marketSpreads.add(marketSpreadObjects[i]);
}
}
if (calibrationTimes.size() < 2) {
throw new OpenGammaRuntimeException("Need at least two credit spread points for pricing");
}
final ValueProperties properties = desiredValues.iterator().next().getConstraints().copy()
.with(ValuePropertyNames.FUNCTION, getUniqueId())
.get();
return getComputedValue(definition, yieldCurve, volatility, calibrationTimes.toArray(new ZonedDateTime[calibrationTimes.size()]),
marketSpreads.toDoubleArray(), hazardRateCurve, valuationTime, target, properties);
}
@Override
public ComputationTargetType getTargetType() {
return FinancialSecurityTypes.CREDIT_DEFAULT_SWAP_OPTION_SECURITY;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties properties = ValueProperties.all();
final Set<ValueSpecification> results = new HashSet<>();
for (final String valueRequirement : _valueRequirements) {
results.add(new ValueSpecification(valueRequirement, target.toSpecification(), properties));
}
return results;
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> yieldCurveNames = constraints.getValues(PROPERTY_YIELD_CURVE);
if (yieldCurveNames == null || yieldCurveNames.size() != 1) {
return null;
}
final Set<String> yieldCurveCalculationConfigNames = constraints.getValues(PROPERTY_YIELD_CURVE_CALCULATION_CONFIG);
if (yieldCurveCalculationConfigNames == null || yieldCurveCalculationConfigNames.size() != 1) {
return null;
}
final Set<String> yieldCurveCalculationMethodNames = constraints.getValues(PROPERTY_YIELD_CURVE_CALCULATION_METHOD);
if (yieldCurveCalculationMethodNames == null || yieldCurveCalculationMethodNames.size() != 1) {
return null;
}
// final Set<String> hazardRateCurveNames = constraints.getValues(PROPERTY_HAZARD_RATE_CURVE);
// if (hazardRateCurveNames == null || hazardRateCurveNames.size() != 1) {
// return null;
final Set<String> hazardRateCurveCalculationMethodNames = constraints.getValues(PROPERTY_HAZARD_RATE_CURVE_CALCULATION_METHOD);
if (hazardRateCurveCalculationMethodNames == null || hazardRateCurveCalculationMethodNames.size() != 1) {
return null;
}
// final Set<String> volatilitySurfaceNames = constraints.getValues(SURFACE);
// if (volatilitySurfaceNames == null || volatilitySurfaceNames.size() != 1) {
// return null;
final SecuritySource securitySource = OpenGammaCompilationContext.getSecuritySource(context);
final CreditSecurityToIdentifierVisitor identifierVisitor = new CreditSecurityToIdentifierVisitor(securitySource);
final CreditDefaultSwapOptionSecurity security = (CreditDefaultSwapOptionSecurity) target.getSecurity();
final String spreadCurveName = security.accept(identifierVisitor).getUniqueId().getValue();
//TODO need to handle surface data as well
final ComputationTargetSpecification currencyTarget = ComputationTargetSpecification.of(FinancialSecurityUtils.getCurrency(target.getSecurity()));
final String yieldCurveName = Iterables.getOnlyElement(yieldCurveNames);
final String yieldCurveCalculationConfigName = Iterables.getOnlyElement(yieldCurveCalculationConfigNames);
final String yieldCurveCalculationMethodName = Iterables.getOnlyElement(yieldCurveCalculationMethodNames);
final ValueRequirement yieldCurveRequirement = YieldCurveFunctionUtils.getCurveRequirement(currencyTarget, yieldCurveName, yieldCurveCalculationConfigName,
yieldCurveCalculationMethodName);
//final String hazardRateCurveName = Iterables.getOnlyElement(hazardRateCurveNames);
final String hazardRateCurveCalculationMethod = Iterables.getOnlyElement(hazardRateCurveCalculationMethodNames);
final Set<String> creditSpreadCurveShifts = constraints.getValues(PROPERTY_SPREAD_CURVE_SHIFT);
final ValueProperties.Builder hazardRateCurveProperties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE, spreadCurveName)
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, hazardRateCurveCalculationMethod)
.with(PROPERTY_YIELD_CURVE_CALCULATION_CONFIG, yieldCurveCalculationConfigName)
.with(PROPERTY_YIELD_CURVE_CALCULATION_METHOD, yieldCurveCalculationMethodName)
.with(PROPERTY_YIELD_CURVE, yieldCurveName);
final ValueProperties.Builder spreadCurveProperties = ValueProperties.builder()
.with(CURVE, spreadCurveName);
if (creditSpreadCurveShifts != null) {
hazardRateCurveProperties.with(PROPERTY_SPREAD_CURVE_SHIFT, creditSpreadCurveShifts);
spreadCurveProperties.with(PROPERTY_SPREAD_CURVE_SHIFT, creditSpreadCurveShifts);
}
final ValueRequirement creditSpreadCurveRequirement = new ValueRequirement(ValueRequirementNames.CREDIT_SPREAD_CURVE, ComputationTargetSpecification.NULL, spreadCurveProperties.get());
final ValueRequirement hazardRateCurveRequirement = new ValueRequirement(ValueRequirementNames.HAZARD_RATE_CURVE, target.toSpecification(), hazardRateCurveProperties.get());
// final String volatilitySurfaceName = Iterables.getOnlyElement(volatilitySurfaceNames);
// final ValueProperties volatilityProperties = ValueProperties.builder()
// .with(SURFACE, volatilitySurfaceName)
// .get();
// final ValueRequirement volSurfaceRequirement = new ValueRequirement(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, ComputationTargetSpecification.NULL, volatilityProperties);
return Sets.newHashSet(yieldCurveRequirement, creditSpreadCurveRequirement, hazardRateCurveRequirement); //, volSurfaceRequirement);
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) {
final ValueProperties.Builder propertiesBuilder = getCommonResultProperties();
for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) {
final ValueSpecification spec = entry.getKey();
final ValueProperties.Builder inputPropertiesBuilder = spec.getProperties().copy();
inputPropertiesBuilder.withoutAny(FUNCTION);
final String valueName = spec.getValueName();
if (valueName.equals(ValueRequirementNames.YIELD_CURVE)) {
propertiesBuilder.with(PROPERTY_YIELD_CURVE, inputPropertiesBuilder.get().getValues(CURVE));
inputPropertiesBuilder.withoutAny(CURVE);
propertiesBuilder.with(PROPERTY_YIELD_CURVE_CALCULATION_CONFIG, inputPropertiesBuilder.get().getValues(CURVE_CALCULATION_CONFIG));
inputPropertiesBuilder.withoutAny(CURVE_CALCULATION_CONFIG);
propertiesBuilder.with(PROPERTY_YIELD_CURVE_CALCULATION_METHOD, inputPropertiesBuilder.get().getValues(CURVE_CALCULATION_METHOD));
inputPropertiesBuilder.withoutAny(CURVE_CALCULATION_METHOD);
} else if (valueName.equals(ValueRequirementNames.CREDIT_SPREAD_CURVE)) {
propertiesBuilder.with(PROPERTY_SPREAD_CURVE, inputPropertiesBuilder.get().getValues(CURVE));
inputPropertiesBuilder.withoutAny(CURVE);
} else if (valueName.equals(ValueRequirementNames.HAZARD_RATE_CURVE)) {
propertiesBuilder.with(PROPERTY_HAZARD_RATE_CURVE, inputPropertiesBuilder.get().getValues(CURVE));
inputPropertiesBuilder.withoutAny(CURVE);
propertiesBuilder.with(PROPERTY_HAZARD_RATE_CURVE_CALCULATION_METHOD, inputPropertiesBuilder.get().getValues(CURVE_CALCULATION_METHOD));
inputPropertiesBuilder.withoutAny(CURVE_CALCULATION_METHOD);
}
final ValueProperties inputProperties = inputPropertiesBuilder.get();
if (!inputProperties.isEmpty()) {
for (final String propertyName : inputProperties.getProperties()) {
propertiesBuilder.with(propertyName, inputProperties.getValues(propertyName));
}
}
}
if (labelResultWithCurrency()) {
propertiesBuilder.with(CURRENCY, FinancialSecurityUtils.getCurrency(target.getSecurity()).getCode());
}
final ValueProperties properties = propertiesBuilder.get();
final ComputationTargetSpecification targetSpec = target.toSpecification();
final Set<ValueSpecification> results = new HashSet<>();
for (final String valueRequirement : _valueRequirements) {
results.add(new ValueSpecification(valueRequirement, targetSpec, properties));
}
return results;
}
protected abstract Set<ComputedValue> getComputedValue(CreditDefaultSwapOptionDefinition definition, ISDADateCurve yieldCurve, double vol, ZonedDateTime[] calibrationTenors,
double[] marketSpreads, HazardRateCurve hazardRateCurve, ZonedDateTime valuationTime, ComputationTarget target, ValueProperties properties);
protected abstract boolean labelResultWithCurrency();
protected abstract ValueProperties.Builder getCommonResultProperties();
}
|
package org.csstudio.opibuilder.widgets.editparts;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.opibuilder.editparts.AbstractPVWidgetEditPart;
import org.csstudio.opibuilder.editparts.ExecutionMode;
import org.csstudio.opibuilder.model.AbstractPVWidgetModel;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler;
import org.csstudio.opibuilder.widgets.figures.ComboFigure;
import org.csstudio.opibuilder.widgets.model.ComboModel;
import org.csstudio.simplepv.IPV;
import org.csstudio.simplepv.IPVListener;
import org.csstudio.simplepv.VTypeHelper;
import org.diirt.vtype.VEnum;
import org.diirt.vtype.VType;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Combo;
/**The editpart of a combo.
*
* @author Xihui Chen
*
*/
public final class ComboEditPart extends AbstractPVWidgetEditPart {
private IPVListener loadItemsFromPVListener;
private Combo combo;
private SelectionListener comboSelectionListener;
/**
* {@inheritDoc}
*/
@Override
protected IFigure doCreateFigure() {
final ComboModel model = getWidgetModel();
updatePropSheet(model.isItemsFromPV());
ComboFigure comboFigure = new ComboFigure(this);
combo = comboFigure.getSWTWidget();
List<String> items = getWidgetModel().getItems();
updateCombo(items);
markAsControlPV(AbstractPVWidgetModel.PROP_PVNAME, AbstractPVWidgetModel.PROP_PVVALUE);
return comboFigure;
}
/**
* @param items
*/
private void updateCombo(List<String> items) {
if(items !=null && getExecutionMode() == ExecutionMode.RUN_MODE){
combo.removeAll();
for(String item : items){
combo.add(item);
}
//write value to pv if pv name is not empty
if(getWidgetModel().getPVName().trim().length() > 0){
if(comboSelectionListener !=null)
combo.removeSelectionListener(comboSelectionListener);
comboSelectionListener = new SelectionAdapter(){
@Override
public void widgetSelected(SelectionEvent e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Combo click " + e);
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Button 1 " + (e.stateMask & SWT.BUTTON1));
Logger.getLogger(getClass().getName()).log(Level.SEVERE, SWT.getPlatform());
// Only react if the selection was accomplished
// by clicking on an item.
if (e.stateMask == SWT.BUTTON1)
setPVValue(AbstractPVWidgetModel.PROP_PVNAME, combo.getText());
else
{ // Ignore selections from mouse wheel (stateMask == 0).
// Unfortunately this also ignores selections via keyboard,
// which has been discussed in
// Restore current value to UI.
final String current = VTypeHelper.getString((VType)getPropertyValue(ComboModel.PROP_PVVALUE));
final int sel = Arrays.asList(combo.getItems()).indexOf(current);
if (sel >= 0)
combo.select(sel);
else
combo.deselectAll();
}
}
};
combo.addSelectionListener(comboSelectionListener);
}
}
}
@Override
public ComboModel getWidgetModel() {
return (ComboModel)getModel();
}
@Override
protected void doActivate() {
super.doActivate();
registerLoadItemsListener();
}
private void registerLoadItemsListener() {
//load items from PV
if(getExecutionMode() == ExecutionMode.RUN_MODE){
if(getWidgetModel().isItemsFromPV()){
IPV pv = getPV(AbstractPVWidgetModel.PROP_PVNAME);
if(pv != null){
if(loadItemsFromPVListener == null)
loadItemsFromPVListener = new IPVListener.Stub() {
@Override
public void valueChanged(IPV pv) {
VType value = pv.getValue();
if (value != null && value instanceof VEnum){
List<String> items = ((VEnum)value).getLabels();
getWidgetModel().setPropertyValue(
ComboModel.PROP_ITEMS, items);
}
}
};
pv.addListener(loadItemsFromPVListener);
}
}
}
}
@Override
protected void doDeActivate() {
super.doDeActivate();
if(getWidgetModel().isItemsFromPV()){
IPV pv = getPV(AbstractPVWidgetModel.PROP_PVNAME);
if(pv != null && loadItemsFromPVListener !=null){
pv.removeListener(loadItemsFromPVListener);
}
}
// ((ComboFigure)getFigure()).dispose();
}
/**
* {@inheritDoc}
*/
@Override
protected void registerPropertyChangeHandlers() {
IWidgetPropertyChangeHandler pvNameHandler = new IWidgetPropertyChangeHandler() {
@Override
public boolean handleChange(Object oldValue, Object newValue, IFigure figure) {
registerLoadItemsListener();
return false;
}
};
setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVNAME, pvNameHandler);
autoSizeWidget((ComboFigure) getFigure());
// PV_Value
IWidgetPropertyChangeHandler pvhandler = new IWidgetPropertyChangeHandler() {
@Override
public boolean handleChange(final Object oldValue,
final Object newValue, final IFigure refreshableFigure) {
if(newValue != null){
String stringValue = VTypeHelper.getString((VType)newValue);
if(Arrays.asList(combo.getItems()).contains(stringValue))
combo.setText(stringValue);
else
combo.deselectAll();
// if(getWidgetModel().isBorderAlarmSensitve())
// autoSizeWidget((ComboFigure) refreshableFigure);
}
return true;
}
};
setPropertyChangeHandler(ComboModel.PROP_PVVALUE, pvhandler);
// Items
IWidgetPropertyChangeHandler itemsHandler = new IWidgetPropertyChangeHandler() {
@SuppressWarnings("unchecked")
@Override
public boolean handleChange(final Object oldValue,
final Object newValue, final IFigure refreshableFigure) {
if(newValue != null && newValue instanceof List){
updateCombo((List<String>)newValue);
if(getWidgetModel().isItemsFromPV())
combo.setText(VTypeHelper.getString(getPVValue(AbstractPVWidgetModel.PROP_PVNAME)));
}
return true;
}
};
setPropertyChangeHandler(ComboModel.PROP_ITEMS, itemsHandler);
final IWidgetPropertyChangeHandler handler = new IWidgetPropertyChangeHandler() {
@Override
public boolean handleChange(final Object oldValue,
final Object newValue, final IFigure refreshableFigure) {
updatePropSheet((Boolean) newValue);
return false;
}
};
getWidgetModel().getProperty(ComboModel.PROP_ITEMS_FROM_PV).
addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent evt) {
handler.handleChange(evt.getOldValue(), evt.getNewValue(), getFigure());
}
});
//size change handlers--always apply the default height
IWidgetPropertyChangeHandler handle = new IWidgetPropertyChangeHandler() {
@Override
public boolean handleChange(final Object oldValue, final Object newValue,
final IFigure figure) {
autoSizeWidget((ComboFigure)figure);
return true;
}
};
setPropertyChangeHandler(AbstractWidgetModel.PROP_WIDTH, handle);
setPropertyChangeHandler(AbstractWidgetModel.PROP_HEIGHT, handle);
setPropertyChangeHandler(AbstractWidgetModel.PROP_BORDER_STYLE, handle);
setPropertyChangeHandler(AbstractWidgetModel.PROP_BORDER_WIDTH, handle);
setPropertyChangeHandler(ComboModel.PROP_FONT, handle);
}
/**
* @param actionsFromPV
*/
private void updatePropSheet(final boolean itemsFromPV) {
getWidgetModel().setPropertyVisible(
ComboModel.PROP_ITEMS, !itemsFromPV);
}
private void autoSizeWidget(ComboFigure comboFigure) {
Dimension d = comboFigure.getAutoSizeDimension();
getWidgetModel().setSize(getWidgetModel().getWidth(), d.height);
}
@Override
public String getValue() {
return combo.getText();
}
@Override
public void setValue(Object value) {
if(value instanceof String)
combo.setText((String) value);
else if (value instanceof Number)
combo.select(((Number)value).intValue());
else
super.setValue(value);
}
}
|
package org.camunda.bpm.spring.boot.starter.example.dmn.rest;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.impl.util.json.JSONArray;
import org.camunda.bpm.engine.impl.util.json.JSONObject;
import org.camunda.bpm.engine.repository.DecisionDefinition;
import org.camunda.bpm.spring.boot.starter.CamundaBpmProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.slf4j.LoggerFactory.getLogger;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {DmnRestApplication.class})
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
@DirtiesContext
public class DmnRestApplicationTest {
private static final String CHECK_ORDER = "checkOrder";
@Value("${local.server.port}")
private int port;
@Autowired
private CamundaBpmProperties camundaBpmProperties;
private final Logger logger = getLogger(this.getClass());
@Autowired
private RepositoryService repositoryService;
@Test
public void deploys_orderDiscount_dmn() {
final DecisionDefinition definition = repositoryService.createDecisionDefinitionQuery()
.decisionDefinitionKey(CHECK_ORDER)
.singleResult();
assertThat(definition).isNotNull();
}
@Test
public void evaluate_checkOrder() throws InterruptedException {
String url = String.format("http://localhost:%d/rest/engine/%s/decision-definition/key/%s/evaluate",
port,
camundaBpmProperties.getProcessEngineName(),
CHECK_ORDER);
String JSONInput = "{\n" +
" \"variables\" : {\n" +
" \"status\" : { \"value\" : \"silver\", \"type\" : \"String\" },\n" +
" \"sum\" : { \"value\" : 900, \"type\" : \"Integer\" }\n" +
" }\n" +
"}\n";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity request= new HttpEntity(JSONInput, headers);
final String check = new TestRestTemplate().postForObject(url, request, String.class);
assertThat(new JSONArray(check).getJSONObject(0)
.getJSONObject("result")
.getString("value")).isEqualTo("ok");
}
}
|
package com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.grouping;
import com.centurylink.cloud.sdk.servers.client.domain.group.DiskUsageMetadata;
import com.centurylink.cloud.sdk.servers.client.domain.group.GuestUsageMetadata;
import com.centurylink.cloud.sdk.servers.client.domain.group.SamplingEntry;
import com.centurylink.cloud.sdk.servers.client.domain.group.ServerMonitoringStatistics;
import com.centurylink.cloud.sdk.servers.services.domain.group.refs.Group;
import com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.DiskUsage;
import com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.GuestUsage;
import com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.MonitoringEntry;
import com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.MonitoringStatsEntry;
import com.centurylink.cloud.sdk.servers.services.domain.statistics.monitoring.filter.MonitoringStatsFilter;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toList;
public abstract class GroupMonitoringStatsBy {
protected MonitoringStatsFilter statsFilter;
public abstract List<MonitoringStatsEntry> group(Map<Group, List<ServerMonitoringStatistics>> monitoringStats);
public GroupMonitoringStatsBy(MonitoringStatsFilter statsFilter) {
checkNotNull(statsFilter, "Filter must be not a null");
this.statsFilter = statsFilter;
}
protected List<MonitoringEntry> convertEntry(List<SamplingEntry> entries) {
return entries.stream()
.map(entry -> new MonitoringEntry()
.timestamp(entry.getTimestamp())
.cpu(entry.getCpu())
.cpuPercent(entry.getCpuPercent())
.diskUsageTotalCapacityMB(entry.getDiskUsageTotalCapacityMB())
.memoryMB(entry.getMemoryMB())
.memoryPercent(entry.getMemoryPercent())
.networkReceivedKBps(entry.getNetworkReceivedKbps())
.networkTransmittedKBps(entry.getNetworkTransmittedKbps())
.diskUsage(convertDiskUsage(entry.getDiskUsage()))
.guestDiskUsage(convertGuestUsage(entry.getGuestDiskUsage()))
)
.collect(toList());
}
protected List<DiskUsage> convertDiskUsage(List<DiskUsageMetadata> list) {
return list.stream()
.map(metadata -> new DiskUsage()
.id(metadata.getId())
.capacityMB(metadata.getCapacityMB()))
.collect(toList());
}
protected List<GuestUsage> convertGuestUsage(List<GuestUsageMetadata> list) {
return list.stream()
.map(metadata -> new GuestUsage()
.path(metadata.getPath())
.capacityMB(metadata.getCapacityMB())
.consumedMB(metadata.getConsumedMB()))
.collect(toList());
}
protected void collectStats(Map<String, List<MonitoringEntry>> plainGrouping,
String key,
List<SamplingEntry> stats,
boolean distinct) {
if (!plainGrouping.containsKey(key)) {
plainGrouping.put(key, convertEntry(stats));
return;
}
if (!distinct) {
plainGrouping.get(key).addAll(convertEntry(stats));
}
}
protected List<ServerMonitoringStatistics> selectServersStatsDistinct(
Map<Group, List<ServerMonitoringStatistics>> stats) {
Map<String, ServerMonitoringStatistics> distinctMap = new HashMap<>();
stats.values().stream()
.flatMap(List::stream)
.forEach(stat -> {
if (!distinctMap.containsKey(stat.getName())) {
distinctMap.put(stat.getName(), stat);
}
});
return new ArrayList<>(distinctMap.values());
}
@SuppressWarnings("unchecked")
protected <T> MonitoringStatsEntry createMonitoringStatsEntry(T metadata, List<MonitoringEntry> entries) {
return new MonitoringStatsEntry<>(metadata, entries);
}
@SuppressWarnings("unchecked")
protected List<MonitoringStatsEntry> aggregate(List<MonitoringStatsEntry> plainEntries) {
return plainEntries.stream()
.map(entry -> {
List<MonitoringEntry> resultEntries = ((List<OffsetDateTime>) entry.getStatistics().stream()
//select distinct timestamps
.map(e -> ((MonitoringEntry) e).getTimestamp())
.distinct()
.collect(toList()))
.stream()
.map(time -> aggregateMonitoringEntry(entry, time))
.collect(toList());
return new MonitoringStatsEntry(entry.getEntity(), resultEntries);
})
.collect(toList());
}
@SuppressWarnings("unchecked")
private MonitoringEntry aggregateMonitoringEntry(MonitoringStatsEntry entry, OffsetDateTime time) {
Supplier<Stream<MonitoringEntry>> streamSupplier =
() -> entry.getStatistics().stream()
.filter(e -> ((MonitoringEntry) e).getTimestamp().equals(time));
long entriesCount = streamSupplier.get().count();
return new MonitoringEntry()
.timestamp(time)
.cpu(
streamSupplier.get().collect(summingInt(MonitoringEntry::getCpu)))
.cpuPercent(
streamSupplier.get().collect(summingDouble(MonitoringEntry::getCpuPercent)) / entriesCount)
.diskUsageTotalCapacityMB(
streamSupplier.get().collect(summingInt(MonitoringEntry::getDiskUsageTotalCapacityMB)))
.memoryMB(
streamSupplier.get().collect(summingInt(MonitoringEntry::getMemoryMB)))
.memoryPercent(
streamSupplier.get().collect(summingDouble(MonitoringEntry::getMemoryPercent)) / entriesCount)
.networkReceivedKBps(
streamSupplier.get().collect(summingDouble(MonitoringEntry::getNetworkReceivedKBps)))
.networkTransmittedKBps(
streamSupplier.get().collect(summingDouble(MonitoringEntry::getNetworkTransmittedKBps)))
.diskUsage(aggregateDiskUsage(
streamSupplier.get().map(MonitoringEntry::getDiskUsage).flatMap(List::stream).collect(toList())))
.guestDiskUsage(aggregateGuestUsage(
streamSupplier.get().map(MonitoringEntry::getGuestDiskUsage).flatMap(List::stream).collect(toList())));
}
private List<DiskUsage> aggregateDiskUsage(List<DiskUsage> flatList) {
HashMap<String, List<DiskUsage>> map = new HashMap<>();
flatList.stream()
.forEach(item -> {
if (map.get(item.getId()) == null) {
map.put(item.getId(), new ArrayList<>());
}
map.get(item.getId()).add(new DiskUsage().id(item.getId()).capacityMB(item.getCapacityMB()));
});
return map.keySet().stream()
.map(key ->
new DiskUsage()
.id(key)
.capacityMB(
map.get(key).stream()
.collect(summingInt(DiskUsage::getCapacityMB)))
)
.collect(toList());
}
private List<GuestUsage> aggregateGuestUsage(List<GuestUsage> flatList) {
HashMap<String, List<GuestUsage>> map = new HashMap<>();
flatList.stream()
.forEach(item -> {
if (map.get(item.getPath()) == null) {
map.put(item.getPath(), new ArrayList<>());
}
map.get(item.getPath()).add(
new GuestUsage()
.path(item.getPath())
.capacityMB(item.getCapacityMB())
.consumedMB(item.getConsumedMB())
);
});
return map.keySet().stream()
.map(key ->
new GuestUsage()
.path(key)
.capacityMB(
map.get(key).stream()
.collect(summingInt(GuestUsage::getCapacityMB)))
.consumedMB(
map.get(key).stream()
.collect(summingInt(GuestUsage::getConsumedMB)))
)
.collect(toList());
}
}
|
package org.csstudio.display.builder.representation.javafx.widgets;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.csstudio.display.builder.model.DirtyFlag;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.widgets.SymbolWidget;
import org.csstudio.javafx.Styles;
import org.diirt.vtype.VType;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
/**
* @author claudiorosati, European Spallation Source ERIC
* @version 1.0.0 19 Jun 2017
*/
public class SymbolRepresentation extends RegionBaseRepresentation<StackPane, SymbolWidget> {
private static final Executor EXECUTOR = Executors.newFixedThreadPool(8);
private Node content;
private final DirtyFlag dirtyGeometry = new DirtyFlag();
private final DirtyFlag dirtyStyle = new DirtyFlag();
private final DirtyFlag dirtyValue = new DirtyFlag();
private volatile boolean enabled = true;
private final Label indexLabel = new Label();
private final Circle indexLabelBackground = new Circle(16.0, Color.BLACK.deriveColor(0.0, 0.0, 0.0, 0.75));
private IntegerProperty imageIndex = new SimpleIntegerProperty(-1);
private int getImageIndex ( ) {
return imageIndex.get();
}
private IntegerProperty imageIndexProperty ( ) {
return imageIndex;
}
private void setImageIndex ( int imageIndex ) {
// EXECUTOR.execute(() -> {
// updatingSymbols.lock();
// try {
// Platform.runLater(() -> this.imageIndex.set(imageIndex));
// } finally {
// updatingSymbols.unlock();
}
@Override
public void updateChanges ( ) {
super.updateChanges();
// boolean needsSVGResize = false;
Object value;
if ( dirtyGeometry.checkAndClear() ) {
value = model_widget.propVisible().getValue();
if ( !Objects.equals(value, jfx_node.isVisible()) ) {
jfx_node.setVisible((boolean) value);
}
// value = model_widget.propAutoSize().getValue();
// if ( !Objects.equals(value, autoSize) ) {
// autoSize = (boolean) value;
// if ( autoSize ) {
// model_widget.propWidth().setValue((int) Math.round(maxSize.getWidth()));
// model_widget.propHeight().setValue((int) Math.round(maxSize.getHeight()));
double w = model_widget.propWidth().getValue();
double h = model_widget.propHeight().getValue();
if ( w < 32 || h < 32 ) {
jfx_node.getChildren().remove(indexLabel);
jfx_node.getChildren().remove(indexLabelBackground);
} else {
if ( !jfx_node.getChildren().contains(indexLabelBackground) ) {
jfx_node.getChildren().add(indexLabelBackground);
}
if ( !jfx_node.getChildren().contains(indexLabel) ) {
jfx_node.getChildren().add(indexLabel);
}
}
jfx_node.setLayoutX(model_widget.propX().getValue());
jfx_node.setLayoutY(model_widget.propY().getValue());
jfx_node.setPrefSize(w, h);
if ( content != null ) {
if ( content instanceof DefaultSymbol ) {
((DefaultSymbol) content).setSize(w, h);
} else if ( content instanceof Region ) {
((Region) content).setPrefSize(w, h);
}
}
// double minSize = Math.min(w, h);
// indexLabelBackground.setRadius(Math.min(minSize / 2, 16.0));
// needsSVGResize = true;
}
// if ( dirtyIndex.checkAndClear() ) {
// setImageIndex(model_widget.propInitialIndex().getValue());
// if ( dirtyContent.checkAndClear() ) {
// value = model_widget.propArrayIndex().getValue();
// if ( !Objects.equals(value, arrayIndex) ) {
// arrayIndex = Math.max(0, (int) value);
// dirtyValue.mark();
if ( dirtyStyle.checkAndClear() ) {
// value = model_widget.propPreserveRatio().getValue();
// if ( !Objects.equals(value, imageView.isPreserveRatio()) ) {
// imageView.setPreserveRatio((boolean) value);
// needsSVGResize = true;
value = model_widget.propEnabled().getValue();
if ( !Objects.equals(value, enabled) ) {
enabled = (boolean) value;
Styles.update(jfx_node, Styles.NOT_ENABLED, !enabled);
}
value = model_widget.propShowIndex().getValue();
if ( !Objects.equals(value, indexLabel.isVisible()) ) {
indexLabel.setVisible((boolean) value);
indexLabelBackground.setVisible((boolean) value);
}
// if ( model_widget.propTransparent().getValue() ) {
// jfx_node.setBackground(null);
// } else {
// jfx_node.setBackground(new Background(new BackgroundFill(JFXUtil.convert(model_widget.propBackgroundColor().getValue()), CornerRadii.EMPTY, Insets.EMPTY)));
// value = model_widget.propRotation().getValue();
// if ( !Objects.equals(value, imagePane.getRotate()) ) {
// imagePane.setRotate((double) value);
}
// if ( dirtyValue.checkAndClear() && updatingValue.compareAndSet(false, true) ) {
// int idx = Integer.MIN_VALUE; // Marker indicating no valid value.
// try {
// value = model_widget.runtimePropValue().getValue();
// if ( value != null ) {
// if ( PVWidget.RUNTIME_VALUE_NO_PV == value ) {
// idx = model_widget.propInitialIndex().getValue();
// } else if ( value instanceof VBoolean ) {
// idx = ( (VBoolean) value ).getValue() ? 1 : 0;
// } else if ( value instanceof VString ) {
// try {
// idx = Integer.parseInt(( (VString) value ).getValue());
// } catch ( NumberFormatException nfex ) {
// logger.log(Level.FINE, "Failure parsing the string value: {0} [{1}].", new Object[] { ( (VString) value ).getValue(), nfex.getMessage() });
// } else if ( value instanceof VNumber ) {
// idx = ( (VNumber) value ).getValue().intValue();
// } else if ( value instanceof VEnum ) {
// idx = ( (VEnum) value ).getIndex();
// } else if ( value instanceof VNumberArray ) {
// ListNumber array = ( (VNumberArray) value ).getData();
// if ( array.size() > 0 ) {
// idx = array.getInt(Math.min(arrayIndex, array.size() - 1));
// } else if ( value instanceof VEnumArray ) {
// ListInt array = ( (VEnumArray) value ).getIndexes();
// if ( array.size() > 0 ) {
// idx = array.getInt(Math.min(arrayIndex, array.size() - 1));
// } finally {
// updatingValue.set(false);
// if ( idx != Integer.MIN_VALUE ) {
// // Valid value.
// setImageIndex(idx);
// if ( needsSVGResize ) {
// imagesList.stream().filter(ic -> ic.isSVG()).forEach(ic -> {
// double widgetWidth = model_widget.propWidth().getValue().doubleValue();
// double widgetHeight = model_widget.propHeight().getValue().doubleValue();
// double symbolWidth = widgetWidth;
// double symbolHeight = widgetHeight;
// if ( model_widget.propPreserveRatio().getValue() ) {
// double wPrime = symbolHeight * ic.getOriginalRatio();
// double hPrime = symbolWidth / ic.getOriginalRatio();
// if ( wPrime < symbolWidth ) {
// symbolHeight = hPrime;
// } else if ( hPrime < symbolHeight ) {
// symbolWidth = wPrime;
// double finalSymbolWidth = symbolWidth;
// double finalSymbolHeight = symbolHeight;
// double cos_a = Math.cos(Math.toRadians(model_widget.propRotation().getValue()));
// double sin_a = Math.sin(Math.toRadians(model_widget.propRotation().getValue()));
// double pic_bb_w = symbolWidth * Math.abs(cos_a) + symbolHeight * Math.abs(sin_a);
// double pic_bb_h = symbolWidth * Math.abs(sin_a) + symbolHeight * Math.abs(cos_a);
// double scale_fac = Math.min(widgetWidth / pic_bb_w, widgetHeight / pic_bb_h);
// if ( scale_fac < 1.0 ) {
// finalSymbolWidth = (int) Math.floor(scale_fac * symbolWidth);
// finalSymbolHeight = (int) Math.floor(scale_fac * symbolHeight);
// SVG svg = ic.getSVG();
// Bounds bounds = svg.getLayoutBounds();
// double boundsWidth = bounds.getWidth();
// double boundsHeight = bounds.getHeight();
// svg.setScaleX(finalSymbolWidth / boundsWidth);
// svg.setScaleY(finalSymbolHeight / boundsHeight);
// if ( finalSymbolWidth < boundsWidth && widgetWidth <= boundsWidth ) {
// svg.setTranslateX(( widgetWidth - boundsWidth ) / 2.0);
// } else {
// svg.setTranslateX(0);
// if ( finalSymbolHeight < boundsHeight && widgetHeight <= boundsHeight ) {
// svg.setTranslateY(( widgetHeight - boundsHeight ) / 2.0);
// } else {
// svg.setTranslateY(0);
}
@Override
protected StackPane createJFXNode ( ) throws Exception {
// setImageIndex(Math.max(model_widget.propInitialIndex().getValue(), 0));
// autoSize = model_widget.propAutoSize().getValue();
content = new DefaultSymbol();
StackPane symbol = new StackPane();
// imagePane = new BorderPane();
// imageView = new ImageView();
// imageView.setPreserveRatio(model_widget.propPreserveRatio().getValue());
// imageView.setSmooth(true);
// imageView.fitHeightProperty().bind(symbol.prefHeightProperty());
// imageView.fitWidthProperty().bind(symbol.prefWidthProperty());
// imageView.imageProperty().bind(Bindings.createObjectBinding(
// () -> getDisplayable(ic -> ic.isImage(), ic -> ic.getImage(), getDefaultSymbol()),
// imageIndexProperty(),
// triggerImageUpdateProperty()
// imagePane.setPrefWidth(model_widget.propWidth().getValue());
// imagePane.setPrefHeight(model_widget.propHeight().getValue());
// imagePane.setRotate(model_widget.propRotation().getValue());
// imagePane.centerProperty().bind(Bindings.createObjectBinding(
// () -> getDisplayable(ic -> ic.isSVG(), ic -> ic.getSVG(), imageView),
// imageIndexProperty(),
// triggerContentUpdateProperty()
// AnchorPane.setLeftAnchor(imagePane, 0.0);
// AnchorPane.setRightAnchor(imagePane, 0.0);
// AnchorPane.setTopAnchor(imagePane, 0.0);
// AnchorPane.setBottomAnchor(imagePane, 0.0);
indexLabelBackground.setStroke(Color.LIGHTGRAY.deriveColor(0.0, 1.0, 1.0, 0.75));
indexLabelBackground.setVisible(model_widget.propShowIndex().getValue());
indexLabel.setAlignment(Pos.CENTER);
indexLabel.setFont(Font.font(indexLabel.getFont().getFamily(), FontWeight.BOLD, 16));
indexLabel.setTextFill(Color.WHITE);
indexLabel.setVisible(model_widget.propShowIndex().getValue());
indexLabel.textProperty().bind(Bindings.convert(imageIndexProperty()));
symbol.getChildren().addAll(content, indexLabelBackground, indexLabel);
// if ( model_widget.propTransparent().getValue() ) {
// symbol.setBackground(null);
// } else {
// symbol.setBackground(new Background(new BackgroundFill(JFXUtil.convert(model_widget.propBackgroundColor().getValue()), CornerRadii.EMPTY, Insets.EMPTY)));
// enabled = model_widget.propEnabled().getValue();
// Styles.update(symbol, Styles.NOT_ENABLED, !enabled);
// imageChanged(null, null, null);
return symbol;
}
@Override
protected void registerListeners ( ) {
super.registerListeners();
// model_widget.propArrayIndex().addUntypedPropertyListener(this::contentChanged);
// model_widget.propPVName().addPropertyListener(this::contentChanged);
// model_widget.propSymbols().addPropertyListener(this::imagesChanged);
// model_widget.propSymbols().getValue().stream().forEach(p -> {
// p.removePropertyListener(imagePropertyListener);
// p.addPropertyListener(imagePropertyListener);
// model_widget.propInitialIndex().addPropertyListener(this::initialIndexChanged);
// model_widget.propAutoSize().addUntypedPropertyListener(this::geometryChanged);
// model_widget.propVisible().addUntypedPropertyListener(this::geometryChanged);
// model_widget.propX().addUntypedPropertyListener(this::geometryChanged);
// model_widget.propY().addUntypedPropertyListener(this::geometryChanged);
model_widget.propWidth().addUntypedPropertyListener(this::geometryChanged);
model_widget.propHeight().addUntypedPropertyListener(this::geometryChanged);
// model_widget.propBackgroundColor().addUntypedPropertyListener(this::styleChanged);
model_widget.propEnabled().addUntypedPropertyListener(this::styleChanged);
// model_widget.propPreserveRatio().addUntypedPropertyListener(this::styleChanged);
// model_widget.propRotation().addUntypedPropertyListener(this::styleChanged);
model_widget.propShowIndex().addUntypedPropertyListener(this::styleChanged);
// model_widget.propTransparent().addUntypedPropertyListener(this::styleChanged);
// if ( toolkit.isEditMode() ) {
// dirtyValue.checkAndClear();
// } else {
// model_widget.runtimePropValue().addPropertyListener(this::valueChanged);
// valueChanged(null, null, null);
}
private void geometryChanged ( final WidgetProperty<?> property, final Object oldValue, final Object newValue ) {
dirtyGeometry.mark();
toolkit.scheduleUpdate(this);
}
private void styleChanged ( final WidgetProperty<?> property, final Object oldValue, final Object newValue ) {
dirtyStyle.mark();
toolkit.scheduleUpdate(this);
}
private void valueChanged ( final WidgetProperty<? extends VType> property, final VType oldValue, final VType newValue ) {
dirtyValue.mark();
toolkit.scheduleUpdate(this);
}
private class DefaultSymbol extends Group {
private final Rectangle r;
private final Line l1;
private final Line l2;
DefaultSymbol() {
setAutoSizeChildren(true);
setManaged(true);
int w = 100;
int h = 100;
r = new Rectangle(0, 0, w, h);
r.setFill(null);
r.setArcHeight(0);
r.setArcWidth(0);
r.setStroke(Color.BLACK);
r.setStrokeType(StrokeType.INSIDE);
l1 = new Line(0.5, 0.5, w - 0.5, h - 0.5);
l1.setStroke(Color.BLACK);
l1.setStrokeLineCap(StrokeLineCap.BUTT);
l2 = new Line(0.5, h - 0.5, w - 0.5, 0.5);
l2.setStroke(Color.BLACK);
l2.setStrokeLineCap(StrokeLineCap.BUTT);
getChildren().add(r);
getChildren().add(l1);
getChildren().add(l2);
}
public void setSize ( double w, double h ) {
r.setWidth(w);
r.setHeight(h);
l1.setEndX(w - 0.5);
l1.setEndY(h - 0.5);
l2.setEndX(w - 0.5);
l2.setStartY(h - 0.5);
}
}
// private static volatile Image defaultSymbol = null;
// private int arrayIndex = 0;
// private volatile boolean autoSize = false;
// private final DirtyFlag dirtyContent = new DirtyFlag();
// private final DirtyFlag dirtyIndex = new DirtyFlag();
// private final List<ImageContent> imagesList = Collections.synchronizedList(new ArrayList<>(4));
// private final Map<String, ImageContent> imagesMap = Collections.synchronizedMap(new TreeMap<>());
// private BorderPane imagePane;
// private final WidgetPropertyListener<String> imagePropertyListener = this::imageChanged;
// private ImageView imageView;
// private Dimension2D maxSize = new Dimension2D(0, 0);
// private final ReentrantLock updatingSymbols = new ReentrantLock();
// private final AtomicBoolean updatingValue = new AtomicBoolean(false);
// private BooleanProperty triggerContentUpdate = new SimpleBooleanProperty(false);
// private boolean isTriggerContentUpdate ( ) {
// return triggerContentUpdate.get();
// private BooleanProperty triggerContentUpdateProperty ( ) {
// return triggerContentUpdate;
// private void setTriggerContentUpdate ( boolean triggerContentUpdate ) {
// Platform.runLater(() -> this.triggerContentUpdate.set(triggerContentUpdate));
// private void triggerContentUpdate() {
// setTriggerContentUpdate(!isTriggerContentUpdate());
// private BooleanProperty triggerImageUpdate = new SimpleBooleanProperty(false);
// private boolean isTriggerImageUpdate ( ) {
// return triggerImageUpdate.get();
// private BooleanProperty triggerImageUpdateProperty ( ) {
// return triggerImageUpdate;
// private void setTriggerImageUpdate ( boolean triggerImageUpdate ) {
// Platform.runLater(() -> this.triggerImageUpdate.set(triggerImageUpdate));
// private void triggerImageUpdate() {
// setTriggerImageUpdate(!isTriggerImageUpdate());
// /**
// * Compute the maximum width and height of the given {@code widget} based on
// * the its set of symbol images.
// *
// * @param widget The {@link SymbolWidget} whose size must be computed.
// * @return A not {@code null} maximum dimension of the given {@code widget}.
// */
// public static Dimension2D computeMaximumSize ( final SymbolWidget widget ) {
// Double[] max_size = new Double[] { 0.0, 0.0 };
// widget.propSymbols().getValue().stream().forEach(s -> {
// final String imageFile = s.getValue();
// try {
// final SymbolRepresentation representation = widget.getUserData(Widget.USER_DATA_REPRESENTATION);
// final ImageContent ic = representation.imagesMap.containsKey(imageFile)
// ? representation.imagesMap.get(imageFile)
// : representation.createImageContent(imageFile);
// if ( max_size[0] < ic.getOriginalWidth() ) {
// max_size[0] = ic.getOriginalWidth();
// if ( max_size[1] < ic.getOriginalHeight() ) {
// max_size[1] = ic.getOriginalHeight();
// } catch ( Exception ex ) {
// // The following message has proven to be annoying and not useful.
// //logger.log(Level.WARNING, "Cannot obtain image size for {0} [{1}].", new Object[] { imageFile, ex.getMessage() });
// return new Dimension2D(max_size[0], max_size[1]);
// public static String resolveImageFile ( SymbolWidget widget, String imageFileName ) {
// try {
// String expandedFileName = MacroHandler.replace(widget.getMacrosOrProperties(), imageFileName);
// // Resolve new image file relative to the source widget model (not 'top'!).
// // Get the display model from the widget tied to this representation.
// final DisplayModel widgetModel = widget.getDisplayModel();
// // Resolve the image path using the parent model file path.
// return ModelResourceUtil.resolveResource(widgetModel, expandedFileName);
// } catch ( Exception ex ) {
// logger.log(Level.WARNING, "Failure resolving image path: {0} [{1}].", new Object[] { imageFileName, ex.getMessage() });
// return null;
// private static boolean resourceExists ( String fileName ) {
// try {
// ModelResourceUtil.openResourceStream(fileName);
// } catch ( Exception ex ) {
// return false;
// return true;
// @Override
// public void dispose ( ) {
// super.dispose();
// private void contentChanged ( final WidgetProperty<?> property, final Object oldValue, final Object newValue ) {
// dirtyContent.mark();
// toolkit.scheduleUpdate(this);
// private ImageContent createImageContent ( String fileName ) {
// return new ImageContent(fileName);
// private Image getDefaultSymbol() {
// if ( defaultSymbol == null ) {
// synchronized ( SymbolRepresentation.class ) {
// if ( defaultSymbol == null ) {
// defaultSymbol = loadDefaultSymbol();
// return defaultSymbol;
// private <T> T getDisplayable( Predicate<ImageContent> predicate, Function<ImageContent, T> getter, T defaultDisplayable ) {
// int index = getImageIndex();
// if ( index >= 0 && index < imagesList.size() ) {
// ImageContent imageContent = imagesList.get(index);
// if ( predicate.test(imageContent) ) {
// return getter.apply(imageContent);
// } else {
// return defaultDisplayable;
// } else {
// return defaultDisplayable;
// private void imageChanged ( final WidgetProperty<String> property, final String oldValue, final String newValue ) {
// EXECUTOR.execute(() -> {
// updateSymbols();
// dirtyContent.mark();
// toolkit.scheduleUpdate(this);
// private void imagesChanged ( final WidgetProperty<List<WidgetProperty<String>>> property, final List<WidgetProperty<String>> oldValue, final List<WidgetProperty<String>> newValue ) {
// EXECUTOR.execute(() -> {
// updateSymbols();
// if ( oldValue != null ) {
// oldValue.stream().forEach(p -> p.removePropertyListener(imagePropertyListener));
// if ( newValue != null ) {
// newValue.stream().forEach(p -> p.addPropertyListener(imagePropertyListener));
// dirtyContent.mark();
// toolkit.scheduleUpdate(this);
// private void initialIndexChanged ( final WidgetProperty<?> property, final Object oldValue, final Object newValue ) {
// dirtyIndex.mark();
// toolkit.scheduleUpdate(this);
// private Image loadDefaultSymbol() {
// String imageFileName = resolveImageFile(model_widget, SymbolWidget.DEFAULT_SYMBOL);
// try {
// // Open the image from the stream created from the resource file.
// return new Image(ModelResourceUtil.openResourceStream(imageFileName));
// } catch ( Exception ex ) {
// logger.log(Level.WARNING, "Failure loading image: {0} [{1}].", new Object[] { SymbolWidget.DEFAULT_SYMBOL, ex.getMessage() });
// return null;
// /**
// * Fix the file names imported from BOY.
// */
// private void updateImportedSymbols ( ) {
// try {
// ArrayWidgetProperty<WidgetProperty<String>> propSymbols = model_widget.propSymbols();
// List<String> fileNames = new ArrayList<>(2);
// switch ( model_widget.getImportedFrom() ) {
// case "org.csstudio.opibuilder.widgets.ImageBoolIndicator":
// return;
// case "org.csstudio.opibuilder.widgets.symbol.bool.BoolMonitorWidget": {
// String imageFileName = propSymbols.getElement(0).getValue();
// int dotIndex = imageFileName.lastIndexOf('.');
// String onImageFileName = imageFileName.substring(0, dotIndex) + " On" + imageFileName.substring(dotIndex);
// String offImageFileName = imageFileName.substring(0, dotIndex) + " Off" + imageFileName.substring(dotIndex);
// if ( resourceExists(resolveImageFile(model_widget, onImageFileName)) ) {
// fileNames.add(onImageFileName);
// } else {
// fileNames.add(imageFileName);
// if ( resourceExists(resolveImageFile(model_widget, offImageFileName)) ) {
// fileNames.add(offImageFileName);
// } else {
// fileNames.add(imageFileName);
// break;
// case "org.csstudio.opibuilder.widgets.symbol.multistate.MultistateMonitorWidget": {
// String imageFileName = propSymbols.getElement(0).getValue();
// int dotIndex = imageFileName.lastIndexOf('.');
// int spaceIndex = imageFileName.lastIndexOf(' ');
// try {
// model_widget.propInitialIndex().setValue(Integer.parseInt(imageFileName.substring(1 + spaceIndex, dotIndex)));
// } catch ( NumberFormatException nfex ) {
// logger.log(Level.WARNING, "Imported image file doesn't contain state value [{0}].", imageFileName);
// int index = 0;
// while ( true ) {
// String nthImageFileName = MessageFormat.format(
// "{0} {1,number,
// imageFileName.substring(0, spaceIndex),
// index,
// imageFileName.substring(dotIndex)
// if ( resourceExists(resolveImageFile(model_widget, nthImageFileName)) ) {
// fileNames.add(nthImageFileName);
// } else {
// break;
// index++;
// break;
// default:
// logger.log(Level.WARNING, "Invalid imported type [{0}].", model_widget.getImportedFrom());
// return;
// for ( int i = 0; i < fileNames.size(); i++ ) {
// model_widget.addOrReplaceSymbol(i, fileNames.get(i));
// } finally {
// model_widget.clearImportedFrom();
// private synchronized void updateSymbols ( ) {
// updatingSymbols.lock();
// try {
// int oldIndex = getImageIndex();
// try {
// ArrayWidgetProperty<WidgetProperty<String>> propSymbols = model_widget.propSymbols();
// List<WidgetProperty<String>> fileNames = propSymbols.getValue();
// if ( model_widget.getImportedFrom() != null ) {
// updateImportedSymbols();
// if ( fileNames == null ) {
// logger.log(Level.WARNING, "Empty list of file names.");
// } else {
// imagesList.clear();
// fileNames.stream().forEach(f -> {
// String fileName = f.getValue();
// ImageContent imageContent = imagesMap.get(fileName);
// if ( imageContent == null ) {
// imageContent = createImageContent(fileName);
// if ( imageContent.isValid() ) {
// imagesMap.put(fileName, imageContent);
// if ( imageContent.isValid() ) {
// imagesList.add(imageContent);
// Set<String> toBeRemoved = imagesMap.keySet().stream().filter(f -> !imagesList.contains(imagesMap.get(f))).collect(Collectors.toSet());
// toBeRemoved.stream().forEach(f -> imagesMap.remove(f));
// } finally {
// int newImageIndex = Math.min(Math.max(getImageIndex(), 0), imagesList.size() - 1);
// maxSize = computeMaximumSize(model_widget);
// if ( oldIndex == newImageIndex && oldIndex >= 0 ) {
// ImageContent imageContent = imagesList.get(getImageIndex());
// if ( imageContent.isSVG() || ( imageContent.isImage() && imagePane.getCenter() != imageView ) ) {
// Platform.runLater(() -> triggerContentUpdate());
// } else if ( imageContent.isImage() ) {
// Platform.runLater(() -> triggerImageUpdate());
// } else if ( oldIndex != newImageIndex ) {
// setImageIndex(newImageIndex);
// dirtyGeometry.mark();
// dirtyValue.mark();
// toolkit.scheduleUpdate(this);
// } finally {
// updatingSymbols.unlock();
// private class ImageContent {
// private Image image;
// private double originalHeight;
// private double originalWidth;
// private SVG svg;
// ImageContent ( String fileName ) {
// boolean loadFailed = true;
// String imageFileName = resolveImageFile(model_widget, fileName);
// if ( imageFileName != null ) {
// if ( imageFileName.toLowerCase().endsWith(".svg") ) {
// try {
// // Open the image from the stream created from the resource file
// svg = SVG.load(ModelResourceUtil.openResourceStream(imageFileName));
// Bounds bounds = svg.getLayoutBounds();
// originalWidth = bounds.getWidth();
// originalHeight = bounds.getHeight();
// image = null;
// loadFailed = false;
// } catch ( Exception ex ) {
// logger.log(Level.WARNING, "Failure loading SVG image file: ({0}) {1} [{2}].", new Object[] { fileName, imageFileName, ex.getMessage() });
// } else {
// try {
// // Open the image from the stream created from the resource file.
// image = new Image(ModelResourceUtil.openResourceStream(imageFileName));
// originalWidth = image.getWidth();
// originalHeight = image.getHeight();
// svg = null;
// loadFailed = false;
// } catch ( Exception ex ) {
// logger.log(Level.WARNING, "Failure loading image: ({0}) {1} [{2}].", new Object[] { fileName, imageFileName, ex.getMessage() });
// if ( loadFailed ) {
// imageFileName = resolveImageFile(model_widget, SymbolWidget.DEFAULT_SYMBOL);
// try {
// // Open the image from the stream created from the resource file.
// image = getDefaultSymbol();
// originalWidth = image.getWidth();
// originalHeight = image.getHeight();
// svg = null;
// } catch ( Exception ex ) {
// logger.log(Level.WARNING, "Failure loading image: ({0}) {1} [{2}].", new Object[] { fileName, imageFileName, ex.getMessage() });
// image = null;
// svg = null;
// originalWidth = Double.NaN;
// originalHeight = Double.NaN;
// Image getImage() {
// return image;
// double getOriginalHeight() {
// return originalHeight;
// double getOriginalRatio() {
// return originalWidth / originalHeight;
// double getOriginalWidth() {
// return originalWidth;
// SVG getSVG() {
// return svg;
// boolean isImage() {
// return ( image != null );
// boolean isSVG() {
// return ( svg != null );
// boolean isValid() {
// return ( isImage() || isSVG() );
}
|
package org.openhab.persistence.influxdb.internal;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Pong;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.openhab.core.items.GroupItem;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.library.items.ColorItem;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.DateTimeItem;
import org.openhab.core.library.items.DimmerItem;
import org.openhab.core.library.items.LocationItem;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.HSBType;
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.PointType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.persistence.FilterCriteria;
import org.openhab.core.persistence.FilterCriteria.Ordering;
import org.openhab.core.persistence.HistoricItem;
import org.openhab.core.persistence.PersistenceService;
import org.openhab.core.persistence.QueryablePersistenceService;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit.RetrofitError;
public class InfluxDBPersistenceService implements QueryablePersistenceService {
private static final String DEFAULT_URL = "http://127.0.0.1:8086";
private static final String DEFAULT_DB = "openhab";
private static final String DEFAULT_USER = "openhab";
private static final String DEFAULT_RETENTION_POLICY = "autogen";
private static final String DIGITAL_VALUE_OFF = "0";
private static final String DIGITAL_VALUE_ON = "1";
private static final String VALUE_COLUMN_NAME = "value";
private static final String VALUE_COLUMN_STRING_NAME = "value-string";
private static final String VALUE_COLUMN_INTEGER_NAME = "value-integer";
private static final String VALUE_COLUMN_DOUBLE_NAME = "value-double";
private static final String TYPE_COLUMN_NAME = "type-name";
private static final String ITEM_NAME_TAG = "item-name";
private ItemRegistry itemRegistry;
private InfluxDB influxDB;
private static final Logger logger = LoggerFactory.getLogger(InfluxDBPersistenceService.class);
private static final String TIME_COLUMN_NAME = "time";
private static final TimeUnit timeUnit = TimeUnit.MILLISECONDS;
private String dbName;
private String url;
private String user;
private String password;
private String retentionPolicy;
private String measurementName;
private boolean isProperlyConfigured;
private boolean connected;
public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
public void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
public void activate(final BundleContext bundleContext, final Map<String, Object> config) {
logger.debug("influxdb persistence service activated");
disconnect();
password = (String) config.get("password");
if (isBlank(password)) {
isProperlyConfigured = false;
logger.error("influxdb:password",
"The password is missing. To specify a password configure the password parameter in openhab.cfg.");
return;
}
url = (String) config.get("url");
if (isBlank(url)) {
url = DEFAULT_URL;
logger.debug("using default url {}", DEFAULT_URL);
}
user = (String) config.get("user");
if (isBlank(user)) {
user = DEFAULT_USER;
logger.debug("using default user {}", DEFAULT_USER);
}
dbName = (String) config.get("db");
if (isBlank(dbName)) {
dbName = DEFAULT_DB;
logger.debug("using default db name {}", DEFAULT_DB);
}
retentionPolicy = (String) config.get("retentionPolicy");
if (isBlank(retentionPolicy)) {
retentionPolicy = DEFAULT_RETENTION_POLICY;
logger.debug("using default retentionPolicy {}", DEFAULT_RETENTION_POLICY);
}
measurementName = (String) config.get("combined_measurements");
if (isBlank(measurementName)) {
logger.debug("Using default storage schema");
} else {
logger.debug("Putting all values in central combined_measurements");
}
isProperlyConfigured = true;
connect();
// check connection; errors will only be logged, hoping the connection will work at a later
// time.
if (!checkConnection()) {
logger.error("database connection does not work for now, will retry to use the database.");
}
}
public void deactivate() {
logger.debug("influxdb persistence service deactivated");
disconnect();
}
private void connect() {
if (influxDB == null) {
// reuse an existing InfluxDB object because concerning the database it has no state
// connection
influxDB = InfluxDBFactory.connect(url, user, password);
influxDB.enableBatch(200, 100, timeUnit);
}
connected = true;
}
private boolean checkConnection() {
boolean dbStatus = false;
if (!connected) {
logger.error("checkConnection: database is not connected");
dbStatus = false;
} else {
try {
Pong pong = influxDB.ping();
String version = pong.getVersion();
// may be check for version >= 0.9
if (version != null && !version.contains("unknown")) {
dbStatus = true;
logger.debug("database status is OK, version is {}", version);
} else {
logger.error("database ping error, version is: \"{}\" response time was \"{}\"", version,
pong.getResponseTime());
dbStatus = false;
}
} catch (RuntimeException e) {
dbStatus = false;
logger.error("database connection failed", e);
handleDatabaseException(e);
}
}
return dbStatus;
}
private void disconnect() {
influxDB = null;
connected = false;
}
private boolean isConnected() {
return connected;
}
@Override
public String getName() {
return "influxdb";
}
@Override
public void store(Item item) {
store(item, null);
}
/**
* {@inheritDoc}
*/
@Override
public void store(Item item, String alias) {
if (item.getState() instanceof UnDefType) {
return;
}
if (!isProperlyConfigured) {
logger.warn("Configuration for influxdb not yet loaded or broken.");
return;
}
if (!isConnected()) {
logger.warn("InfluxDB is not yet connected");
return;
}
String realName = item.getName();
String name = (alias != null) ? alias : realName;
State state = null;
if (item.getAcceptedCommandTypes().contains(HSBType.class)) {
state = item.getStateAs(HSBType.class);
logger.trace("Tried to get item as {}, state is {}", HSBType.class, state.toString());
} else if (item.getAcceptedDataTypes().contains(PercentType.class)) {
state = item.getStateAs(PercentType.class);
logger.trace("Tried to get item as {}, state is {}", PercentType.class, state.toString());
} else {
// All other items should return the best format by default
state = item.getState();
logger.trace("Tried to get item from item class {}, state is {}", item.getClass(), state.toString());
}
Point point;
if (isBlank(measurementName)) {
Object value = stateToObject(state);
logger.trace("storing {} in influxdb value {}, {}", name, value, item);
point = Point.measurement(name).field(VALUE_COLUMN_NAME, value).time(System.currentTimeMillis(), timeUnit)
.build();
} else {
point = stateToPoint(item);
logger.trace("storing point {}", point);
}
try {
influxDB.write(dbName, retentionPolicy, point);
} catch (RuntimeException e) {
logger.error("storing failed with exception for item: {}", name);
handleDatabaseException(e);
}
}
private void handleDatabaseException(Exception e) {
if (e instanceof RetrofitError) {
// e.g. raised if influxdb is not running
logger.error("database connection error {}", e.getMessage());
} else if (e instanceof RuntimeException) {
// e.g. raised by authentication errors
logger.error("database error: {}", e.getMessage());
}
}
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
logger.debug("got a query");
if (!isProperlyConfigured) {
logger.warn("Configuration for influxdb not yet loaded or broken.");
return Collections.emptyList();
}
if (!isConnected()) {
logger.warn("InfluxDB is not yet connected");
return Collections.emptyList();
}
List<HistoricItem> historicItems = new ArrayList<HistoricItem>();
StringBuffer query;
if (!isBlank(measurementName)) {
query = getSingleMeasurementQuery(filter);
} else {
query = getMultiMeasurementQuery(filter);
}
logger.trace(
"Filter: itemname: {}, ordering: {}, state: {}, operator: {}, getBeginDate: {}, getEndDate: {}, getPageSize: {}, getPageNumber: {}",
filter.getItemName(), filter.getOrdering().toString(), filter.getState(), filter.getOperator(),
filter.getBeginDate(), filter.getEndDate(), filter.getPageSize(), filter.getPageNumber());
if ((!isBlank(measurementName) || filter.getState() != null && filter.getOperator() != null)
|| filter.getBeginDate() != null || filter.getEndDate() != null) {
query.append(" and ");
boolean foundState = false;
boolean foundBeginDate = false;
if (filter.getState() != null && filter.getOperator() != null) {
String value = stateToString(filter.getState());
if (value != null) {
foundState = true;
query.append(VALUE_COLUMN_NAME);
query.append(" ");
query.append(filter.getOperator().toString());
query.append(" ");
query.append(value);
}
}
if (filter.getBeginDate() != null) {
foundBeginDate = true;
if (foundState) {
query.append(" and");
}
query.append(" ");
query.append(TIME_COLUMN_NAME);
query.append(" > ");
query.append(getTimeFilter(filter.getBeginDate()));
query.append(" ");
}
if (filter.getEndDate() != null) {
if (foundState || foundBeginDate) {
query.append(" and");
}
query.append(" ");
query.append(TIME_COLUMN_NAME);
query.append(" < ");
query.append(getTimeFilter(filter.getEndDate()));
query.append(" ");
}
}
if (filter.getOrdering() == Ordering.DESCENDING) {
query.append(String.format(" ORDER BY %s DESC", TIME_COLUMN_NAME));
logger.debug("descending ordering ");
}
int limit = (filter.getPageNumber() + 1) * filter.getPageSize();
query.append(" limit " + limit);
logger.trace("appending limit {}", limit);
int totalEntriesAffected = ((filter.getPageNumber() + 1) * filter.getPageSize());
int startEntryNum = totalEntriesAffected
- (totalEntriesAffected - (filter.getPageSize() * filter.getPageNumber()));
logger.trace("startEntryNum {}", startEntryNum);
logger.debug("query string: {}", query.toString());
Query influxdbQuery = new Query(query.toString(), dbName);
List<Result> results = Collections.emptyList();
results = influxDB.query(influxdbQuery, timeUnit).getResults();
for (Result result : results) {
List<Series> seriess = result.getSeries();
if (result.getError() != null) {
logger.error(result.getError());
continue;
}
if (seriess == null) {
logger.debug("query returned no series");
} else {
for (Series series : seriess) {
logger.trace("series {}", series.toString());
// TODO: get name
String historicItemName = filter.getItemName();
List<List<Object>> valuess = series.getValues();
if (valuess == null) {
logger.debug("query returned no values");
} else {
List<String> columns = series.getColumns();
logger.trace("columns {}", columns);
Integer timestampColumn = null;
Integer valueColumn = null;
for (int i = 0; i < columns.size(); i++) {
String columnName = columns.get(i);
if (columnName.equals(TIME_COLUMN_NAME)) {
logger.debug("Time: {}", columnName);
timestampColumn = i;
} else if (columnName.equals(VALUE_COLUMN_NAME)) {
valueColumn = i;
} else if (columnName.equals(TYPE_COLUMN_NAME)) {
logger.debug("Type: {}", columnName);
String column_name = valuess.get(0).get(i).toString();
logger.debug("Type-name: {}", column_name);
for (int a = 0; a < columns.size(); a++) {
String columTypeName = columns.get(a);
if (columTypeName.equals(column_name)) {
valueColumn = a;
logger.debug("Type-Index: {}", a);
break;
}
}
}
}
if (valueColumn == null || timestampColumn == null) {
throw new RuntimeException("missing column");
}
for (int i = 0; i < valuess.size(); i++) {
Double rawTime = (Double) valuess.get(i).get(timestampColumn);
Date time = new Date(rawTime.longValue());
State value = objectToState(valuess.get(i).get(valueColumn), historicItemName);
logger.debug("adding historic item {}: time {} value {}", historicItemName, time, value);
historicItems.add(new InfluxdbItem(historicItemName, value, time));
}
}
}
}
}
return historicItems;
}
private StringBuffer getSingleMeasurementQuery(FilterCriteria filter) {
StringBuffer query = new StringBuffer();
query.append("select ").append("*").append(" from \"").append(retentionPolicy).append("\".\"")
.append(measurementName).append("\" ");
if (filter.getItemName() != null) {
query.append("where \"").append(ITEM_NAME_TAG).append("\" = '").append(filter.getItemName()).append("' ");
}
return query;
}
private StringBuffer getMultiMeasurementQuery(FilterCriteria filter) {
StringBuffer query = new StringBuffer();
query.append("select ").append(VALUE_COLUMN_NAME).append(' ').append("from \"").append(retentionPolicy)
.append("\".");
if (filter.getItemName() != null) {
query.append('"').append(filter.getItemName()).append('"');
} else {
query.append("/.*/");
}
return query;
}
private String getTimeFilter(Date time) {
// for some reason we need to query using 'seconds' only
// passing milli seconds causes no results to be returned
long milliSeconds = time.getTime();
long seconds = milliSeconds / 1000;
return seconds + "s";
}
/**
* This method returns an integer if possible if not a double is returned. This is an optimization
* for influxdb because integers have less overhead.
*
* @param value the BigDecimal to be converted
* @return A double if possible else a double is returned.
*/
private Object convertBigDecimalToNum(BigDecimal value) {
Object convertedValue;
if (value.scale() == 0) {
logger.trace("found no fractional part");
convertedValue = value.toBigInteger();
} else {
logger.trace("found fractional part");
convertedValue = value.doubleValue();
}
return convertedValue;
}
/**
* Converts {@link State} to objects fitting into influxdb values.
*
* @param state to be converted
* @return integer or double value for DecimalType, 0 or 1 for OnOffType and OpenClosedType,
* integer for DateTimeType, String for all others
*/
private Object stateToObject(State state) {
Object value;
if (state instanceof HSBType) {
value = ((HSBType) state).toString();
logger.debug("got HSBType value {}", value);
} else if (state instanceof PointType) {
value = point2String((PointType) state);
logger.debug("got PointType value {}", value);
} else if (state instanceof DecimalType) {
value = convertBigDecimalToNum(((DecimalType) state).toBigDecimal());
logger.debug("got DecimalType value {}", value);
} else if (state instanceof OnOffType) {
value = (OnOffType) state == OnOffType.ON ? 1 : 0;
logger.debug("got OnOffType value {}", value);
} else if (state instanceof OpenClosedType) {
value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0;
logger.debug("got OpenClosedType value {}", value);
} else if (state instanceof DateTimeType) {
value = ((DateTimeType) state).getCalendar().getTime().getTime();
logger.debug("got DateTimeType value {}", value);
} else {
value = state.toString();
logger.debug("got String value {}", value);
}
return value;
}
/**
* Converts {@link State} to a String suitable for influxdb queries.
*
* @param state to be converted
* @return {@link String} equivalent of the {@link State}
*/
private String stateToString(State state) {
String value;
if (state instanceof DecimalType) {
value = ((DecimalType) state).toBigDecimal().toString();
} else if (state instanceof PointType) {
value = point2String((PointType) state);
} else if (state instanceof OnOffType) {
value = ((OnOffType) state) == OnOffType.ON ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF;
} else if (state instanceof OpenClosedType) {
value = ((OpenClosedType) state) == OpenClosedType.OPEN ? DIGITAL_VALUE_ON : DIGITAL_VALUE_OFF;
} else if (state instanceof HSBType) {
value = ((HSBType) state).toString();
} else if (state instanceof DateTimeType) {
value = String.valueOf(((DateTimeType) state).getCalendar().getTime().getTime());
} else {
value = state.toString();
}
return value;
}
/**
* Converts a value to a {@link State} which is suitable for the given {@link Item}. This is
* needed for querying a {@link HistoricState}.
*
* @param value to be converted to a {@link State}
* @param itemName name of the {@link Item} to get the {@link State} for
* @return the state of the item represented by the itemName parameter, else the string value of
* the Object parameter
*/
private State objectToState(Object value, String itemName) {
String valueStr = String.valueOf(value);
if (itemRegistry != null) {
try {
Item item = itemRegistry.getItem(itemName);
if (item instanceof GroupItem) {
item = ((GroupItem) item).getBaseItem();
}
if (item instanceof ColorItem) {
logger.debug("objectToState found a ColorItem {}", valueStr);
return new HSBType(valueStr);
} else if (item instanceof LocationItem) {
logger.debug("objectToState found a LocationItem");
return new PointType(valueStr);
} else if (item instanceof NumberItem) {
logger.debug("objectToState found a NumberItem");
return new DecimalType(valueStr);
} else if (item instanceof DimmerItem) {
logger.debug("objectToState found a DimmerItem");
return new PercentType(valueStr);
} else if (item instanceof SwitchItem) {
logger.debug("objectToState found a SwitchItem");
return string2DigitalValue(valueStr).equals(DIGITAL_VALUE_OFF) ? OnOffType.OFF : OnOffType.ON;
} else if (item instanceof ContactItem) {
logger.debug("objectToState found a ContactItem");
return (string2DigitalValue(valueStr).equals(DIGITAL_VALUE_OFF)) ? OpenClosedType.CLOSED
: OpenClosedType.OPEN;
} else if (item instanceof RollershutterItem) {
logger.debug("objectToState found a RollershutterItem");
return new PercentType(valueStr);
} else if (item instanceof DateTimeItem) {
logger.debug("objectToState found a DateItem");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new BigDecimal(valueStr).longValue());
return new DateTimeType(calendar);
} else {
logger.debug("objectToState found a other Item");
return new StringType(valueStr);
}
} catch (ItemNotFoundException e) {
logger.warn("Could not find item '{}' in registry", itemName);
}
}
// just return a StringType as a fallback
return new StringType(valueStr);
}
/**
* Maps a string value which expresses a {@link BigDecimal.ZERO } to DIGITAL_VALUE_OFF, all others
* to DIGITAL_VALUE_ON
*
* @param value to be mapped
* @return
*/
private String string2DigitalValue(String value) {
BigDecimal num = new BigDecimal(value);
if (num.compareTo(BigDecimal.ZERO) == 0) {
logger.trace("digitalvalue {}", DIGITAL_VALUE_OFF);
return DIGITAL_VALUE_OFF;
} else {
logger.trace("digitalvalue {}", DIGITAL_VALUE_ON);
return DIGITAL_VALUE_ON;
}
}
private String point2String(PointType point) {
StringBuffer buf = new StringBuffer();
buf.append(point.getLatitude().toString());
buf.append(",");
buf.append(point.getLongitude().toString());
if (point.getAltitude().equals(0)) {
buf.append(",");
buf.append(point.getAltitude().toString());
}
return buf.toString(); // latitude, longitude, altitude
}
private Point stateToPoint(Item item) {
Point point;
State state = item.getState();
if (state instanceof HSBType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, ((HSBType) state).toString())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got HSBType value {}", point);
} else if (state instanceof PointType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, point2String((PointType) state))
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got PointType value {}", point);
} else if (state instanceof DecimalType) {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_DOUBLE_NAME, ((DecimalType) state).doubleValue())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_DOUBLE_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got DecimalType value {}", point);
} else if (state instanceof OnOffType) {
int value = (OnOffType) state == OnOffType.ON ? 1 : 0;
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got OnOffType value {}", point);
} else if (state instanceof OpenClosedType) {
int value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0;
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got OpenClosedType value {}", point);
} else if (state instanceof DateTimeType) {
long value = ((DateTimeType) state).getCalendar().getTime().getTime();
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_INTEGER_NAME, value).addField(TYPE_COLUMN_NAME, VALUE_COLUMN_INTEGER_NAME)
.time(System.currentTimeMillis(), timeUnit).build();
logger.debug("got DateTimeType value {}", point);
} else {
point = Point.measurement(this.measurementName).tag(ITEM_NAME_TAG, item.getName())
.addField(VALUE_COLUMN_STRING_NAME, state.toString())
.addField(TYPE_COLUMN_NAME, VALUE_COLUMN_STRING_NAME).time(System.currentTimeMillis(), timeUnit)
.build();
logger.debug("got String value {}", point);
}
return point;
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class MainPanel extends JPanel {
protected final JTree tree = new JTree();
protected final JTextField field = new JTextField("b", 10) {
private transient AncestorListener listener;
@Override public void updateUI() {
removeAncestorListener(listener);
super.updateUI();
listener = new FocusAncestorListener();
addAncestorListener(listener);
}
};
protected final JPanel searchBox = new JPanel(new BorderLayout());
protected boolean isHidden = true;
protected int yy;
protected int counter;
protected final Timer animator = new Timer(5, null);
protected final Action showHideAction = new AbstractAction("Show/Hide Search Box") {
@Override public void actionPerformed(ActionEvent e) {
if (!animator.isRunning()) {
// isHidden = !searchBox.isVisible();
isHidden = searchBox.isVisible() ^ true;
searchBox.setVisible(true);
animator.start();
}
}
};
protected final Action hideAction = new AbstractAction("Hide Search Box") {
@Override public void actionPerformed(ActionEvent e) {
if (!animator.isRunning()) {
isHidden = false;
animator.start();
}
}
};
public MainPanel() {
super(new BorderLayout());
animator.addActionListener(e -> {
int height = searchBox.getPreferredSize().height;
double h = height;
if (isHidden) {
yy = (int) (.5 + AnimationUtil.easeInOut(++counter / h) * h);
if (yy >= height) {
yy = height;
animator.stop();
}
} else {
yy = (int) (.5 + AnimationUtil.easeInOut(--counter / h) * h);
if (yy <= 0) {
yy = 0;
animator.stop();
searchBox.setVisible(false);
}
}
searchBox.revalidate();
});
JPanel p = new JPanel() {
@Override public boolean isOptimizedDrawingEnabled() {
return false;
}
};
p.setLayout(new BorderLayout() {
@Override public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int width = parent.getWidth();
int height = parent.getHeight();
int top = insets.top;
int bottom = height - insets.bottom;
int left = insets.left;
int right = width - insets.right;
Component nc = getLayoutComponent(parent, BorderLayout.NORTH);
if (Objects.nonNull(nc)) {
Dimension d = nc.getPreferredSize();
int vsw = UIManager.getInt("ScrollBar.width");
nc.setBounds(right - d.width - vsw, yy - d.height, d.width, d.height);
}
Component cc = getLayoutComponent(parent, BorderLayout.CENTER);
if (Objects.nonNull(cc)) {
cc.setBounds(left, top, right - left, bottom - top);
}
}
}
});
p.add(searchBox, BorderLayout.NORTH);
p.add(new JScrollPane(tree));
tree.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Action findNextAction = new FindNextAction(tree, field);
JButton button = new JButton(findNextAction);
button.setFocusable(false);
button.setToolTipText("Find next");
button.setText("v");
searchBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
searchBox.add(field);
searchBox.add(button, BorderLayout.EAST);
searchBox.setVisible(false);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
// Java 10: int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
InputMap imap = p.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F, modifiers), "open-searchbox");
imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close-searchbox");
p.getActionMap().put("open-searchbox", showHideAction);
p.getActionMap().put("close-searchbox", hideAction);
field.getActionMap().put("find-next", findNextAction);
field.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "find-next");
add(p);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
// frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class FocusAncestorListener implements AncestorListener {
@Override public void ancestorAdded(AncestorEvent e) {
e.getComponent().requestFocusInWindow();
}
@Override public void ancestorMoved(AncestorEvent e) {
/* not needed */
}
@Override public void ancestorRemoved(AncestorEvent e) {
/* not needed */
}
}
class FindNextAction extends AbstractAction {
private final JTree tree;
private final JTextField field;
private final List<TreePath> rollOverPathLists = new ArrayList<>();
protected FindNextAction(JTree tree, JTextField field) {
super();
this.tree = tree;
this.field = field;
}
@Override public void actionPerformed(ActionEvent e) {
TreePath selectedPath = tree.getSelectionPath();
tree.clearSelection();
rollOverPathLists.clear();
searchTree(tree, tree.getPathForRow(0), field.getText(), rollOverPathLists);
if (!rollOverPathLists.isEmpty()) {
int nextIndex = 0;
int size = rollOverPathLists.size();
for (int i = 0; i < size; i++) {
if (rollOverPathLists.get(i).equals(selectedPath)) {
nextIndex = i + 1 < size ? i + 1 : 0;
break;
}
}
TreePath p = rollOverPathLists.get(nextIndex);
tree.addSelectionPath(p);
tree.scrollPathToVisible(p);
}
}
private static void searchTree(JTree tree, TreePath path, String q, List<TreePath> rollOverPathLists) {
Object o = path.getLastPathComponent();
if (o instanceof TreeNode) {
TreeNode node = (TreeNode) o;
if (node.toString().startsWith(q)) {
rollOverPathLists.add(path);
tree.expandPath(path.getParentPath());
}
if (!node.isLeaf()) {
// Java 9: Collections.list(node.children())
Collections.list((Enumeration<?>) node.children())
.forEach(n -> searchTree(tree, path.pathByAddingChild(n), q, rollOverPathLists));
}
}
}
}
final class AnimationUtil {
private static final int N = 3;
private AnimationUtil() {
/* Singleton */
}
// Math: EaseIn EaseOut, EaseInOut and Bezier Curves | Anima Entertainment GmbH
public static double easeIn(double t) {
// range: 0.0 <= t <= 1.0
return Math.pow(t, N);
}
public static double easeOut(double t) {
return Math.pow(t - 1d, N) + 1d;
}
public static double easeInOut(double t) {
double ret;
boolean isFirstHalf = t < .5;
if (isFirstHalf) {
ret = .5 * intpow(t * 2d, N);
} else {
ret = .5 * (intpow(t * 2d - 2d, N) + 2d);
}
return ret;
}
public static double intpow(double da, int ib) {
int b = ib;
if (b < 0) {
throw new IllegalArgumentException("B must be a positive integer or zero");
}
double a = da;
double d = 1d;
for (; b > 0; a *= a, b >>>= 1) {
if ((b & 1) != 0) {
d *= a;
}
}
return d;
}
}
|
package org.wso2.ds.ui.integration.test.dashboard;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.*;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.ds.ui.integration.util.DSUIIntegrationTest;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.net.MalformedURLException;
import static org.testng.Assert.assertEquals;
/**
* This class check whether the custom theme get applied to the dashboard
*/
public class AddCustomThemeToDashboardTest extends DSUIIntegrationTest {
private static final String USER_NAME = "admin";
private static final String PASSWORD = "admin";
private static final String DASHBOARD_TITLE = "sample-dashboard";
private static final String DESCRIPTION = "This is a sample dashboard";
private static final String CUSTOM_THEME_NAME = "custom-theme-sample";
//get the path to custom theme carbon archive file
String systemResourceLocation = FrameworkPathUtil.getSystemResourceLocation();
String carFilePath = systemResourceLocation + "files/Custom_Theme.car";
//get the path to store location of custom themes
String carbonHome = FrameworkPathUtil.getCarbonHome();
String themeStoredLocation = carbonHome + File.separator + "repository" + File.separator + "deployment" +
File.separator + "server" + File.separator + "jaggeryapps" + File.separator + "portal" +
File.separator + "store" + File.separator + "carbon.super" + File.separator + "fs" +
File.separator + "theme" + File.separator + CUSTOM_THEME_NAME;
/**
* Initializes the class.
*
* @param userMode user mode
*/
@Factory(dataProvider = "userMode")
public AddCustomThemeToDashboardTest(TestUserMode userMode) {
super(userMode);
}
/**
* Provides user modes.
*
* @return user modes
*/
@DataProvider(name = "userMode")
public static Object[][] userModeProvider() {
return new Object[][] { { TestUserMode.SUPER_TENANT_ADMIN } };
}
/**
* Setup the testing environment.
*
* @throws MalformedURLException
* @throws XPathExpressionException
* @throws InterruptedException
*/
@BeforeClass(alwaysRun = true)
public void setUp() throws MalformedURLException, XPathExpressionException, InterruptedException {
//log in to admin console
loginToAdminConsole(USER_NAME, PASSWORD);
//deploy the custom theme file
getDriver().findElement(By.xpath("(//a[contains(text(),'Add')])[7]")).click();
getDriver().findElement(By.id("filename")).sendKeys(carFilePath);
getDriver().findElement(By.name("upload")).click();
getDriver().findElement(By.cssSelector("button[type=\"button\"]")).click();
Thread.sleep(15000);
//logout from admin console
logoutFromAdminConsole();
}
/**
* This test method sets the custom theme for the dashboard and check whether it get applied,
* then again change the theme to default theme form the dashboard settings and check whether
* the changes get applied.
*
* @throws XPathExpressionException
* @throws MalformedURLException
* @throws InterruptedException
*/
@Test(groups = "wso2.ds.dashboard", description = "Adding a custom theme when creating a dashboard")
public void addCustomThemeToDashboard() throws XPathExpressionException, MalformedURLException,
InterruptedException {
//log in to portal
login(getCurrentUsername(), getCurrentPassword());
//create dashboard
redirectToLocation(DS_HOME_CONTEXT, DS_DASHBOARDS_CONTEXT);
getDriver().findElement(By.cssSelector("[href='create-dashboard']")).click();
getDriver().findElement(By.id("ues-dashboard-title")).clear();
getDriver().findElement(By.id("ues-dashboard-title")).sendKeys(DASHBOARD_TITLE);
getDriver().findElement(By.id("ues-dashboard-description")).clear();
getDriver().findElement(By.id("ues-dashboard-description")).sendKeys(DESCRIPTION);
//select the custom theme for the dashboard
new Select(getDriver().findElement(By.id("ues-theme-list"))).selectByVisibleText("custom-theme-sample");
getDriver().findElement(By.id("ues-dashboard-create")).click();
selectLayout("default-grid");
//add a page to the dashboard
redirectToLocation(DS_HOME_CONTEXT, DS_DASHBOARDS_CONTEXT);
WebElement webElement = getDriver().findElement(By.id(DASHBOARD_TITLE.toLowerCase()));
webElement.findElement(By.cssSelector(".ues-edit")).click();
addPageToDashboard();
redirectToLocation(DS_HOME_CONTEXT, "dashboards/" + DASHBOARD_TITLE + "/landing");
//check for the dashboard name in the custom theme
assertEquals(getDriver().findElement(By.cssSelector(".product-name")).getText(),
"This is a custom theme title");
//reset the theme to the default theme from the dashboard settings
redirectToLocation(DS_HOME_CONTEXT, "dashboard-settings/" + DASHBOARD_TITLE);
getDriver().findElement(By.xpath("(//button[@type='button'])[2]")).click();
getDriver().findElement(By.linkText("Default Theme")).click();
getDriver().findElement(By.id("ues-dashboard-saveBtn")).click();
Thread.sleep(2000);
redirectToLocation(DS_HOME_CONTEXT, "dashboards/" + DASHBOARD_TITLE + "/landing");
//check for the name in the default theme
assertEquals(getDriver().findElement(By.cssSelector(".product-name")).getText(), DASHBOARD_TITLE);
}
/**
* Clean up after running tests
*
* @throws MalformedURLException
* @throws XPathExpressionException
*/
@AfterClass(alwaysRun = true)
public void tearDown() throws MalformedURLException, XPathExpressionException, InterruptedException {
try {
//log out form the portal
logout();
} finally {
//log in to admin console
loginToAdminConsole(USER_NAME, PASSWORD);
//undeploy custom theme file
getDriver().findElement(By.xpath("(//a[contains(text(),'List')])[6]")).click();
getDriver().findElement(By.linkText("Delete")).click();
getDriver().findElement(By.cssSelector("button[type=\"button\"]")).click();
Thread.sleep(15000);
//logout from admin console
logoutFromAdminConsole();
getDriver().quit();
}
}
}
|
package org.lunifera.web.ecp.uimodel.presentation.vaadin.internal;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.IUiElementEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.IUiViewEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.context.IViewContext;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.extension.IUiCheckboxEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.extension.IUiGridLayoutEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.extension.IUiLabelEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.extension.IUiTextAreaEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.extension.IUiTextFieldEditpart;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.presentation.IPresentationFactory;
import org.eclipse.emf.ecp.ui.uimodel.core.editparts.presentation.IWidgetPresentation;
import org.lunifera.web.ecp.uimodel.presentation.vaadin.VaadinRenderer;
/**
* The presenter factory.
*/
public class PresenterFactory implements IPresentationFactory {
@Override
public boolean isFor(IViewContext uiContext, IUiElementEditpart editpart) {
String presentationURI = uiContext.getPresentationURI();
return presentationURI != null && presentationURI.equals(VaadinRenderer.UI_KIT_URI);
}
@SuppressWarnings("unchecked")
@Override
public <A extends IWidgetPresentation<?>> A createPresentation(IViewContext uiContext, IUiElementEditpart editpart) {
if (editpart instanceof IUiViewEditpart) {
return (A) new ViewPresentation((IUiViewEditpart) editpart);
} else if (editpart instanceof IUiTextFieldEditpart) {
return (A) new TextFieldPresentation(editpart);
} else if (editpart instanceof IUiLabelEditpart) {
return (A) new LabelPresentation(editpart);
} else if (editpart instanceof IUiTextAreaEditpart) {
return (A) new TextAreaPresentation(editpart);
} else if (editpart instanceof IUiCheckboxEditpart) {
return (A) new CheckBoxPresentation(editpart);
} else if (editpart instanceof IUiGridLayoutEditpart) {
return (A) new GridLayoutPresentation(editpart);
}
throw new IllegalArgumentException(String.format("No presenter available for editpart %s[%s]", editpart
.getClass().getName(), editpart.getId()));
}
}
|
package org.innovateuk.ifs.project.status.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.competition.resource.CompetitionOpenQueryResource;
import org.innovateuk.ifs.competition.resource.CompetitionPendingSpendProfilesResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionPostSubmissionRestService;
import org.innovateuk.ifs.project.status.resource.CompetitionProjectsStatusResource;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionOpenQueriesViewModel;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionPendingSpendProfilesViewModel;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionStatusViewModel;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.test.web.servlet.MvcResult;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import static java.lang.String.format;
import static org.hamcrest.Matchers.any;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.project.builder.CompetitionProjectsStatusResourceBuilder.newCompetitionProjectsStatusResource;
import static org.innovateuk.ifs.user.builder.RoleResourceBuilder.newRoleResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class CompetitionStatusControllerTest extends BaseControllerMockMVCTest<CompetitionStatusController> {
@Mock
private CompetitionPostSubmissionRestService competitionPostSubmissionRestService;
@Test
public void testViewCompetitionStatusPage() throws Exception {
Long competitionId = 123L;
mockMvc.perform(get("/competition/" + competitionId + "/status"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/competition/%s/status/all", competitionId)));
}
@Test
public void testViewCompetitionStatusPageAllProjectFinance() throws Exception {
Long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(Arrays.asList(newRoleResource().withType(UserRoleType.PROJECT_FINANCE).build())).build());
CompetitionProjectsStatusResource competitionProjectsStatus = newCompetitionProjectsStatusResource().build();
when(statusRestService.getCompetitionStatus(competitionId)).thenReturn(restSuccess(competitionProjectsStatus));
when(competitionPostSubmissionRestService.getCompetitionOpenQueriesCount(competitionId)).thenReturn(restSuccess(1L));
when(competitionPostSubmissionRestService.countPendingSpendProfiles(competitionId)).thenReturn(restSuccess(4L));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/all"))
.andExpect(view().name("project/competition-status-all"))
.andExpect(model().attribute("model", any(CompetitionStatusViewModel.class)))
.andReturn();
CompetitionStatusViewModel viewModel = (CompetitionStatusViewModel) result.getModelAndView().getModel().get("model");
Assert.assertEquals(1L, viewModel.getOpenQueryCount());
Assert.assertEquals(4L, viewModel.getPendingSpendProfilesCount());
Assert.assertEquals(true, viewModel.isShowTabs());
}
@Test
public void testViewCompetitionStatusPageAllCompAdmin() throws Exception {
Long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(Arrays.asList(newRoleResource().withType(UserRoleType.COMP_ADMIN).build())).build());
CompetitionProjectsStatusResource competitionProjectsStatus = newCompetitionProjectsStatusResource().build();
when(statusRestService.getCompetitionStatus(competitionId)).thenReturn(restSuccess(competitionProjectsStatus));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/all"))
.andExpect(view().name("project/competition-status-all"))
.andExpect(model().attribute("model", any(CompetitionStatusViewModel.class)))
.andReturn();
CompetitionStatusViewModel viewModel = (CompetitionStatusViewModel) result.getModelAndView().getModel().get("model");
Assert.assertEquals(0L, viewModel.getOpenQueryCount());
Assert.assertEquals(0L, viewModel.getPendingSpendProfilesCount());
Assert.assertEquals(false, viewModel.isShowTabs());
verify(competitionPostSubmissionRestService, never()).getCompetitionOpenQueriesCount(competitionId);
verify(competitionPostSubmissionRestService, never()).countPendingSpendProfiles(competitionId);
}
@Test
public void testViewCompetitionStatusPageQueries() throws Exception {
Long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(Arrays.asList(newRoleResource().withType(UserRoleType.PROJECT_FINANCE).build())).build());
CompetitionResource competition = newCompetitionResource().withName("comp1").withId(123L).build();
List<CompetitionOpenQueryResource> openQueries = Arrays.asList(new CompetitionOpenQueryResource(1L, 2L, "org", 3L, "proj"));
when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition));
when(competitionPostSubmissionRestService.getCompetitionOpenQueriesCount(competitionId)).thenReturn(restSuccess(1L));
when(competitionPostSubmissionRestService.getCompetitionOpenQueries(competitionId)).thenReturn(restSuccess(openQueries));
when(competitionPostSubmissionRestService.countPendingSpendProfiles(competitionId)).thenReturn(restSuccess(4L));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/queries"))
.andExpect(view().name("project/competition-status-queries"))
.andExpect(model().attribute("model", any(CompetitionOpenQueriesViewModel.class)))
.andReturn();
CompetitionOpenQueriesViewModel viewModel = (CompetitionOpenQueriesViewModel) result.getModelAndView().getModel().get("model");
Assert.assertEquals(123L, viewModel.getCompetitionId());
Assert.assertEquals("comp1", viewModel.getCompetitionName());
Assert.assertEquals(1L, viewModel.getOpenQueryCount());
Assert.assertEquals(1, viewModel.getOpenQueries().size());
Assert.assertEquals(1L, viewModel.getOpenQueries().get(0).getApplicationId().longValue());
Assert.assertEquals(2L, viewModel.getOpenQueries().get(0).getOrganisationId().longValue());
Assert.assertEquals("org", viewModel.getOpenQueries().get(0).getOrganisationName());
Assert.assertEquals(3L, viewModel.getOpenQueries().get(0).getProjectId().longValue());
Assert.assertEquals("proj", viewModel.getOpenQueries().get(0).getProjectName());
Assert.assertEquals(4L, viewModel.getPendingSpendProfilesCount());
Assert.assertEquals(true, viewModel.isShowTabs());
}
@Test
public void testViewPendingSpendProfiles() throws Exception {
Long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(Arrays.asList(newRoleResource().withType(UserRoleType.PROJECT_FINANCE).build())).build());
CompetitionPendingSpendProfilesResource pendingSpendProfile1 = new CompetitionPendingSpendProfilesResource(11L, 1L, "Project Name 1");
CompetitionPendingSpendProfilesResource pendingSpendProfile2 = new CompetitionPendingSpendProfilesResource(11L, 2L, "Project Name 2");
List<CompetitionPendingSpendProfilesResource> pendingSpendProfiles = Arrays.asList(pendingSpendProfile1, pendingSpendProfile2);
CompetitionResource competition = newCompetitionResource().withName("comp1").withId(123L).build();
when(competitionPostSubmissionRestService.getCompetitionOpenQueriesCount(competitionId)).thenReturn(restSuccess(4L));
when(competitionPostSubmissionRestService.getPendingSpendProfiles(competitionId)).thenReturn(restSuccess(pendingSpendProfiles));
when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/pending-spend-profiles"))
.andExpect(view().name("project/competition-pending-spend-profiles"))
.andExpect(model().attribute("model", any(CompetitionPendingSpendProfilesViewModel.class)))
.andReturn();
CompetitionPendingSpendProfilesViewModel viewModel = (CompetitionPendingSpendProfilesViewModel) result.getModelAndView().getModel().get("model");
Assert.assertEquals(123L, viewModel.getCompetitionId());
Assert.assertEquals("comp1", viewModel.getCompetitionName());
Assert.assertEquals(pendingSpendProfiles, viewModel.getPendingSpendProfiles());
Assert.assertEquals(4L, viewModel.getOpenQueryCount());
Assert.assertEquals(2, viewModel.getPendingSpendProfilesCount());
Assert.assertEquals(true, viewModel.isShowTabs());
}
@Test
public void exportBankDetails() throws Exception {
Long competitionId = 123L;
ByteArrayResource result = new ByteArrayResource("My content!".getBytes());
when(bankDetailsRestService.downloadByCompetition(competitionId)).thenReturn(restSuccess(result));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm");
mockMvc.perform(get("/competition/123/status/bank-details/export"))
.andExpect(status().isOk())
.andExpect(content().contentType(("text/csv")))
.andExpect(header().string("Content-Type", "text/csv"))
.andExpect(header().string("Content-disposition", "attachment;filename=" + String.format("Bank_details_%s_%s.csv", competitionId, ZonedDateTime.now().format(formatter))))
.andExpect(content().string("My content!"));
verify(bankDetailsRestService).downloadByCompetition(123L);
}
@Override
protected CompetitionStatusController supplyControllerUnderTest() {
return new CompetitionStatusController();
}
}
|
package org.corpus_tools.atomic.tokeneditor.configuration;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.layer.IUniqueIndexLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.action.PageUpAction;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultSelectionBindings;
import org.eclipse.nebula.widgets.nattable.ui.action.IKeyAction;
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
import org.eclipse.nebula.widgets.nattable.ui.matcher.KeyEventMatcher;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
/**
* TODO Description
*
* @author Stephan Druskat <mail@sdruskat.net>
*
*/
public class TokenEditorSelectionBindings extends DefaultSelectionBindings {
private final SDocumentGraph graph;
/**
* @param graph
*/
public TokenEditorSelectionBindings(SDocumentGraph graph) {
this.graph = graph;
}
@Override
protected void configurePageDownButtonBindings(UiBindingRegistry uiBindingRegistry, IKeyAction action) {
IKeyAction newAction = new IKeyAction() {
@Override
public void run(NatTable natTable, KeyEvent event) {
// FIXME: Preferentialize the distance value
int distance = 10;
jumpTo(natTable, distance);
}
};
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.NONE, SWT.PAGE_DOWN), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD2, SWT.PAGE_DOWN), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD1, SWT.PAGE_DOWN), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD2 | SWT.MOD1, SWT.PAGE_DOWN), newAction);
}
@Override
protected void configurePageUpButtonBindings(UiBindingRegistry uiBindingRegistry, PageUpAction action) {
IKeyAction newAction = new IKeyAction() {
@Override
public void run(NatTable natTable, KeyEvent event) {
// FIXME: Preferentialize the distance value
int distance = -10;
jumpTo(natTable, distance);
}
};
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.NONE, SWT.PAGE_UP), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD2, SWT.PAGE_UP), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD1, SWT.PAGE_UP), newAction);
uiBindingRegistry.registerKeyBinding(new KeyEventMatcher(SWT.MOD2 | SWT.MOD1, SWT.PAGE_UP), newAction);
}
private void jumpTo(NatTable natTable, int distance) {
SelectionLayer selectionLayer = null;
ILayer underlyingLayer = natTable.getLayer();
if (underlyingLayer instanceof GridLayer) {
ILayer bodyLayer = ((GridLayer) underlyingLayer).getBodyLayer();
if (bodyLayer instanceof ViewportLayer) {
IUniqueIndexLayer scrollLayer = ((ViewportLayer) bodyLayer).getScrollableLayer();
if (scrollLayer instanceof SelectionLayer) {
selectionLayer = (SelectionLayer) scrollLayer;
}
try {
int selectedCol = selectionLayer.getSelectedColumnPositions()[0];
int lastItemIndex = selectionLayer.getColumnCount() - 1;
int jumpPosition = selectedCol + distance;
if (jumpPosition > lastItemIndex) {
jumpPosition = lastItemIndex;
}
else if (jumpPosition < 0) {
jumpPosition = 0;
}
selectionLayer.selectColumn(jumpPosition, 0, false, false);
}
catch (ArrayIndexOutOfBoundsException e) {
// Ignore
}
}
}
}
}
|
package com.googlecode.wickedcharts.showcase.configurations;
import java.util.Arrays;
import com.googlecode.wickedcharts.chartjs.chartoptions.AxesScale;
import com.googlecode.wickedcharts.chartjs.chartoptions.ChartType;
import com.googlecode.wickedcharts.chartjs.chartoptions.Data;
import com.googlecode.wickedcharts.chartjs.chartoptions.Dataset;
import com.googlecode.wickedcharts.chartjs.chartoptions.Options;
import com.googlecode.wickedcharts.chartjs.chartoptions.Scales;
import com.googlecode.wickedcharts.chartjs.chartoptions.Title;
import com.googlecode.wickedcharts.chartjs.chartoptions.TooltipMode;
import com.googlecode.wickedcharts.chartjs.chartoptions.Tooltips;
import com.googlecode.wickedcharts.chartjs.chartoptions.colors.SimpleColor;
import com.googlecode.wickedcharts.showcase.configurations.base.ShowcaseConfiguration;
@SuppressWarnings("serial")
public class StackedGroupChartConfiguration extends ShowcaseConfiguration {
public StackedGroupChartConfiguration() {
setType(ChartType.BAR);
Data data = new Data()
.setLabels(Arrays.asList("January", "February", "March", "April", "May", "June", "July"));
Dataset dataset1 = new Dataset()
.setLabel("Dataset 1")
.setBackgroundColor(SimpleColor.RED)
.setStack(0)
.setData(randomIntegerList(7));
Dataset dataset2 = new Dataset()
.setLabel("Dataset 2")
.setBackgroundColor(SimpleColor.BLUE)
.setStack(0)
.setData(randomIntegerList(7));
Dataset dataset3 = new Dataset()
.setLabel("Dataset 3")
.setBackgroundColor(SimpleColor.GREEN)
.setStack(1)
.setData(randomIntegerList(7));
data.setDatasets(Arrays.asList(dataset1,dataset2,dataset3));
setData(data);
Options options = new Options()
.setTitle(new Title()
.setDisplay(true)
.setText("Chart.js Bar Chart - Stacked"))
.setTooltips(new Tooltips()
.setIntersect(false)
.setMode(TooltipMode.INDEX))
.setResponsive(true)
.setScales(new Scales()
.setXAxes(new AxesScale()
.setStacked(true))
.setYAxes(new AxesScale()
.setStacked(true)));
setOptions(options);
}
}
|
package org.uberfire.security.server.auth.source;
import javax.security.auth.Subject;
import javax.security.jacc.PolicyContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.uberfire.security.SecurityContext;
import org.uberfire.security.auth.Credential;
import org.uberfire.security.impl.auth.UserNameCredential;
import org.uberfire.security.impl.auth.UsernamePasswordCredential;
import org.uberfire.security.server.HttpSecurityContext;
import static org.uberfire.commons.validation.Preconditions.*;
public class HttpServletRequestAuthenticationSource extends JACCAuthenticationSource {
@Override
public boolean supportsCredential( final Credential credential ) {
if ( credential == null ) {
return false;
}
return credential instanceof UserNameCredential;
}
@Override
public boolean authenticate( final Credential credential, final SecurityContext securityContext ) {
try {
final UserNameCredential userNameCredential = checkInstanceOf( "credential", credential, UserNameCredential.class );
final HttpServletRequest request = ((HttpSecurityContext) securityContext).getRequest();
if (request.getUserPrincipal() != null) {
return true;
}
Subject subject = getSubjectFromContainer();
if ( subject != null ) {
return super.authenticate( credential, securityContext );
}
if ( userNameCredential instanceof UsernamePasswordCredential ) {
try {
request.login( userNameCredential.getUserName(), ( (UsernamePasswordCredential) userNameCredential ).getPassword().toString() );
if (subject == null) {
return true;
}
} catch ( final ServletException ex ) {
return false;
}
}
return super.authenticate( credential, securityContext );
} catch ( final Exception e ) {
return false;
}
}
}
|
package gnu.text;
import java.text.*;
import java.text.FieldPosition;
import java.io.Writer;
/** Given a Format, pad the formatted result to a specified width. */
public class PadFormat extends ReportFormat
{
/** Minimum width. */
int minWidth;
char padChar;
/** What percentage of padding appears after the data.
* -1 means internal padding (after initial '-' or '+' or '0x' or '0X'). */
int where;
Format fmt;
public PadFormat(Format fmt, int minWidth, char padChar, int where)
{
this.fmt = fmt;
this.minWidth = minWidth;
this.padChar = padChar;
this.where = where;
}
public PadFormat(Format fmt, int minWidth)
{
this(fmt, minWidth, ' ', 100);
}
public int format(Object[] args, int start,
Writer dst, FieldPosition fpos)
throws java.io.IOException
{
return format(fmt, args, start, dst, padChar, minWidth, 1, 0, where, fpos);
}
public static int padNeeded(int actualWidth,
int minWidth, int colInc, int minPad)
{
int total = actualWidth + minPad;
if (colInc <= 1)
colInc = minWidth - total;
while (total < minWidth)
total += colInc;
return total - actualWidth;
}
public static int format(Format fmt, Object[] args, int start, Writer dst,
char padChar, int minWidth, int colInc, int minPad,
int where, FieldPosition fpos)
throws java.io.IOException
{
/*
if (where == 100)
{
int oldLength = sbuf.length();
fmt.format(obj, sbuf, fpos);
int newLength = sbuf.length();
int pad = padNeeded(newLength - oldLength, minWidth, colInc, minPad);
while (--pad >= 0)
sbuf.append(padChar);
return start + ?;
}
*/
StringBuffer tbuf = new StringBuffer(200);
if (fmt instanceof ReportFormat)
start = ((ReportFormat)fmt).format(args, start, tbuf, fpos);
else if (fmt instanceof MessageFormat)
{
// FIXME - only correct if start == 0.
fmt.format(args, tbuf, fpos);
start = args.length;
}
else
{
fmt.format(args[start], tbuf, fpos);
start++;
}
int len = tbuf.length();
int pad = padNeeded(len, minWidth, colInc, minPad);
int prefix = 0;
String text = tbuf.toString();
if (pad > 0)
{
if (where == -1)
{
if (len > 0)
{
char ch = text.charAt(0);
if (ch == '-' || ch == '+')
{
prefix++;
dst.write(ch);
}
if (len - prefix > 2 && text.charAt(prefix) == '0')
{
dst.write('0');
ch = text.charAt(++prefix);
if (ch == 'x' || ch == 'X')
{
prefix++;
dst.write(ch);
}
}
if (prefix > 0)
text = text.substring(prefix);
}
where = 0;
}
int padAfter = (pad * where) / 100;
int padBefore = pad - padAfter;
/*
if (fpos != null && padBefore > 0)
{
// This is still broken in JDK 1.2 beta2. Check beta3. FIXME.
fpos.setBeginIndex(fpos.getBeginIndex() + padBefore);
fpos.setEndIndex(fpos.getEndIndex() + padBefore);
}
*/
while (--padBefore >= 0)
dst.write(padChar);
dst.write(text);
while (--padAfter >= 0)
dst.write(padChar);
}
else
{
dst.write(text);
}
return start;
}
}
|
package nl.cwi.monetdb.jdbc;
import java.sql.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
/**
* A Statement suitable for the Monet database
* <br /><br />
* The object used for executing a static SQL statement and returning the
* results it produces.<br />
* <br /><br />
* By default, only one ResultSet object per Statement object can be open at the
* same time. Therefore, if the reading of one ResultSet object is interleaved
* with the reading of another, each must have been generated by different
* Statement objects. All execution methods in the Statement interface implicitly
* close a Statement's current ResultSet object if an open one exists.
* <br /><br />
* The current state of this Statement is that it only implements the
* executeQuery() which returns a ResultSet where from results can be read
* and executeUpdate() which doesn't return the affected rows. Commit and
* rollback are implemented, as is the autoCommit mechanism which relies on
* server side auto commit.<br />
* Multi-result queries are supported using the getMoreResults() method.
*
* @author Fabian Groffen <Fabian.Groffen@cwi.nl>
* @version 0.4 (beta release)
*/
public class MonetStatement implements Statement {
/** the default number of rows that are (attempted to) read at once */
static final int DEF_FETCHSIZE = 250;
/** the default value of maxRows, 0 indicates unlimited */
static final int DEF_MAXROWS = 0;
/** the Thread that reads from the server in the background */
final CacheThread cache;
/** A socket connection to Mserver */
private MonetSocket monet;
/** The parental Connection object */
private Connection connection;
/** The last HeaderList object this Statement produced */
private HeaderList lastHeaderList;
/** The last Header that this object uses */
private Header header;
/** The warnings this Statement object generated */
private SQLWarning warnings;
/** Whether this Statement object is closed or not */
private boolean closed;
/** The size of the blocks of results to ask for at the server */
private int fetchSize = DEF_FETCHSIZE;
/** The maximum number of rows to return in a ResultSet */
private int maxRows = DEF_MAXROWS;
/** The suggested direction of fetching data (not really used) */
private int fetchDirection = ResultSet.FETCH_FORWARD;
/** The type of ResultSet to produce; i.e. forward only, random access */
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
/** The concurrency of the ResultSet to produce */
private int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
MonetStatement(
MonetSocket monet,
Connection connection,
int resultSetType,
int resultSetConcurrency)
throws SQLException, IllegalArgumentException
{
if (connection == null) throw
new IllegalArgumentException("No Connection given!");
if (monet == null) throw
new IllegalArgumentException("No connection with the server given!");
this.monet = monet;
this.connection = connection;
this.resultSetType = resultSetType;
this.resultSetConcurrency = resultSetConcurrency;
// check our limits, and generate warnings as appropriate
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
addWarning("No concurrency mode other then read only is supported, continuing with concurrency level READ_ONLY");
resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
}
// check type for supported mode
if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) {
addWarning("Change sensitive scrolling ResultSet objects are not supported, continuing with a change non-sensitive scrollable cursor.");
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
if (resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
setFetchSize(DEF_FETCHSIZE);
} else {
// use smaller blocks when doing scrollable resultsets
setFetchSize(DEF_FETCHSIZE / 10);
}
cache = new CacheThread();
// make the thread a little more important
cache.setPriority(cache.getPriority() + 1);
// quit the VM if it's waiting for this thread to end
cache.setDaemon(true);
cache.start();
closed = false;
}
//== methods of interface Statement
public void addBatch(String sql) {}
public void cancel() {}
public void clearBatch() {}
/**
* Clears all warnings reported for this Statement object. After a call to
* this method, the method getWarnings returns null until a new warning is
* reported for this Statement object.
*/
public void clearWarnings() {
warnings = null;
}
/**
* Releases this Statement object's database and JDBC resources immediately
* instead of waiting for this to happen when it is automatically closed. It
* is generally good practice to release resources as soon as you are
* finished with them to avoid tying up database resources.
* <br /><br />
* Calling the method close on a Statement object that is already closed has
* no effect.
* <br /><br />
* A Statement object is automatically closed when it is garbage collected.
* When a Statement object is closed, its current ResultSet object, if one
* exists, is also closed.
*/
public void close() {
// close previous ResultSet, if not closed already
if (lastHeaderList != null) lastHeaderList.close();
cache.shutdown();
closed = true;
}
// Chapter 13.1.2.3 of Sun's JDBC 3.0 Specification
/**
* Executes the given SQL statement, which may return multiple results. In
* some (uncommon) situations, a single SQL statement may return multiple
* result sets and/or update counts. Normally you can ignore this unless
* you are (1) executing a stored procedure that you know may return
* multiple results or (2) you are dynamically executing an unknown SQL
* string.
* <br /><br />
* The execute method executes an SQL statement and indicates the form of
* the first result. You must then use the methods getResultSet or
* getUpdateCount to retrieve the result, and getMoreResults to move to any
* subsequent result(s).
*
* @param sql any SQL statement
* @return true if the first result is a ResultSet object; false if it is an
* update count or there are no results
* @throws SQLException if a database access error occurs
*/
public boolean execute(String sql) throws SQLException {
// close previous query, if not closed already
if (lastHeaderList != null) {
lastHeaderList.close();
lastHeaderList = null;
}
// let the cache thread do it's work
// use lowercase 's' in order to tell the server we don't want a
// continuation prompt if it needs more to complete the query
// always add ; since that doesn't hurt in any case
lastHeaderList = cache.addQuery("s" + sql + ";");
// give the cache thread a chance to run before we continue blocking
// for it...
Thread.yield();
return(getMoreResults());
}
public boolean execute(String sql, int autoGeneratedKeys) {return(false);}
public boolean execute(String sql, int[] columnIndexed) {return(false);}
public boolean execute(String sql, String[] columnNames) {return(false);}
public int[] executeBatch() {return(null);}
/**
* Executes the given SQL statement, which returns a single ResultSet
* object.
*
* @param sql an SQL statement to be sent to the database, typically a
* static SQL SELECT statement
* @return a ResultSet object that contains the data produced by the given
* query; never null
* @throws SQLException if a database access error occurs or the given SQL
* statement produces anything other than a single ResultSet object
*/
public ResultSet executeQuery(String sql) throws SQLException {
if (execute(sql) != true)
throw new SQLException("Query did not produce a result set");
return(getResultSet());
}
/**
* Executes the given SQL statement, which may be an INSERT, UPDATE, or
* DELETE statement or an SQL statement that returns nothing, such as an
* SQL DDL statement.
* <br /><br />
* make an implementation which returns affected rows, need protocol
* modification for that!!!
*
* @param sql an SQL INSERT, UPDATE or DELETE statement or an SQL statement
* that returns nothing
* @return either the row count for INSERT, UPDATE or DELETE statements, or
* 0 for SQL statements that return nothing<br />
* <b>currently always returns -1 since the mapi protocol doesn't
* return the affected rows!!!</b>
* @throws SQLException if a database access error occurs or the given SQL
* statement produces a ResultSet object
*/
public int executeUpdate(String sql) throws SQLException {
if (execute(sql) != false)
throw new SQLException("Query produced a result set");
return(getUpdateCount());
}
public int executeUpdate(String sql, int autoGeneratedKeys) {return(-1);}
public int executeUpdate(String sql, int[] columnIndexed) {return(-1);}
public int executeUpdate(String sql, String[] columnNames) {return(-1);}
/**
* Retrieves the Connection object that produced this Statement object.
*
* @return the connection that produced this statement
*/
public Connection getConnection() {
return(connection);
}
/**
* Retrieves the direction for fetching rows from database tables that is
* the default for result sets generated from this Statement object. If
* this Statement object has not set a fetch direction by calling the
* method setFetchDirection, the return value is ResultSet.FETCH_FORWARD.
*
* @return the default fetch direction for result sets generated from this
* Statement object
*/
public int getFetchDirection() {
return(fetchDirection);
}
/**
* Retrieves the number of result set rows that is the default fetch size
* for ResultSet objects generated from this Statement object. If this
* Statement object has not set a fetch size by calling the method
* setFetchSize, the return value is DEF_FETCHSIZE.
*
* @return the default fetch size for result sets generated from this
* Statement object
*/
public int getFetchSize() {
return(fetchSize);
}
public ResultSet getGeneratedKeys() {return(null);}
public int getMaxFieldSize() {return(-1);}
/**
* Retrieves the maximum number of rows that a ResultSet object produced by
* this Statement object can contain. If this limit is exceeded, the excess
* rows are silently dropped.
*
* @return the current maximum number of rows for a ResultSet object
* produced by this Statement object; zero means there is no limit
*/
public int getMaxRows() {
return(maxRows);
}
/**
* Moves to this Statement object's next result, returns true if it is a
* ResultSet object, and implicitly closes any current ResultSet object(s)
* obtained with the method getResultSet.
* <br /><br />
* There are no more results when the following is true:<br />
* (!getMoreResults() && (getUpdateCount() == -1)
*
* @return true if the next result is a ResultSet object; false if it is
* an update count or there are no more results
* @throws SQLException if a database access error occurs
* @see #getMoreResults(int current)
*/
public boolean getMoreResults() throws SQLException {
return(getMoreResults(CLOSE_ALL_RESULTS));
}
/**
* Moves to this Statement object's next result, deals with any current
* ResultSet object(s) according to the instructions specified by the given
* flag, and returns true if the next result is a ResultSet object.
* <br /><br />
* There are no more results when the following is true:<br />
* (!getMoreResults() && (getUpdateCount() == -1)
*
* @param current one of the following Statement constants indicating what
* should happen to current ResultSet objects obtained using
* the method getResultSet: CLOSE_CURRENT_RESULT,
* KEEP_CURRENT_RESULT, or CLOSE_ALL_RESULTS
* @return true if the next result is a ResultSet object; false if it is
* an update count or there are no more results
* @throws SQLException if a database access error occurs
*/
public boolean getMoreResults(int current) throws SQLException {
if (current == CLOSE_CURRENT_RESULT) {
if (header != null) header.close();
} else if (current == CLOSE_ALL_RESULTS) {
/// todo: currently not supported
}
// we default to keep current result, which requires no action
header = lastHeaderList.getNextHeader();
if (header == null) {
// no resultset
return(false);
} else {
return(true);
}
}
public int getQueryTimeout() {return(-1);}
/**
* Retrieves the current result as a ResultSet object. This method should
* be called only once per result.
*
* @return the current result as a ResultSet object or null if the result
* is an update count or there are no more results
* @throws SQLException if a database access error occurs
*/
public ResultSet getResultSet() throws SQLException{
if (header == null) return(null);
try {
return(new MonetResultSet(
this,
header,
resultSetType,
resultSetConcurrency));
} catch (IllegalArgumentException e) {
throw new SQLException(e.toString());
}
// don't catch SQLException, it is declared to be thrown
}
/**
* Retrieves the result set concurrency for ResultSet objects generated
* by this Statement object.
*
* @return either ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
*/
public int getResultSetConcurrency() {
return(resultSetConcurrency);
}
public int getResultSetHoldability() {return(-1);}
/**
* Retrieves the result set type for ResultSet objects generated by this
* Statement object.
*
* @return one of ResultSet.TYPE_FORWARD_ONLY,
* ResultSet.TYPE_SCROLL_INSENSITIVE, or
* ResultSet.TYPE_SCROLL_SENSITIVE
*/
public int getResultSetType() {
return(resultSetType);
}
/**
* Retrieves the current result as an update count; if the result is a
* ResultSet object or there are no more results, -1 is returned. This
* method should be called only once per result.
*
* @return the current result as an update count; -1 if the current result
* is a ResultSet object or there are no more results
*/
public int getUpdateCount() {
// there is currently no way to get the update count, so this is fixed
// on -1 for now :(
return(-1);
}
/**
* Retrieves the first warning reported by calls on this Statement object.
* If there is more than one warning, subsequent warnings will be chained to
* the first one and can be retrieved by calling the method
* SQLWarning.getNextWarning on the warning that was retrieved previously.
* <br /><br />
* This method may not be called on a closed statement; doing so will cause
* an SQLException to be thrown.
* <br /><br />
* Note: Subsequent warnings will be chained to this SQLWarning.
*
* @return the first SQLWarning object or null if there are none
* @throws SQLException if a database access error occurs or this method is
* called on a closed connection
*/
public SQLWarning getWarnings() throws SQLException {
if (closed) throw new SQLException("Cannot call on closed Statement");
// if there are no warnings, this will be null, which fits with the
// specification.
return(warnings);
}
public void setCursorName(String name) {}
public void setEscapeProcessing(boolean enable) {}
/**
* Gives the driver a hint as to the direction in which rows will be
* processed in ResultSet objects created using this Statement object.
* The default value is ResultSet.FETCH_FORWARD.
* <br /><br />
* Note that this method sets the default fetch direction for result sets
* generated by this Statement object. Each result set has its own methods
* for getting and setting its own fetch direction.
*
* @param direction the initial direction for processing rows
* @throws SQLException if a database access error occurs or the given
* direction is not one of ResultSet.FETCH_FORWARD,
* ResultSet.FETCH_REVERSE, or ResultSet.FETCH_UNKNOWN
*/
public void setFetchDirection(int direction) throws SQLException {
if (direction == ResultSet.FETCH_FORWARD ||
direction == ResultSet.FETCH_REVERSE ||
direction == ResultSet.FETCH_UNKNOWN)
{
fetchDirection = direction;
} else {
throw new SQLException("Illegal direction: " + direction);
}
}
/**
* Gives the JDBC driver a hint as to the number of rows that should be
* fetched from the database when more rows are needed. The number of rows
* specified affects only result sets created using this statement. If the
* value specified is zero, then the hint is ignored. The default value is
* defined in DEF_FETCHSIZE.<br />
*
* @param rows the number of rows to fetch
* @throws SQLException if the condition 0 <= rows <= this.getMaxRows()
* is not satisfied.
*/
public void setFetchSize(int rows) throws SQLException {
if (rows == 0) {
fetchSize = DEF_FETCHSIZE;
} else if (rows > 0 && !(getMaxRows() != 0 && rows > getMaxRows())) {
fetchSize = rows;
} else {
throw new SQLException("Illegal fetch size value: " + rows);
}
}
public void setMaxFieldSize(int max) {}
/**
* Sets the limit for the maximum number of rows that any ResultSet object
* can contain to the given number. If the limit is exceeded, the excess
* rows are silently dropped.
*
* @param max the new max rows limit; zero means there is no limit
* @throws SQLException if the condition max >= 0 is not satisfied
*/
public void setMaxRows(int max) throws SQLException {
if (max < 0) throw new SQLException("Illegal max value: " + max);
maxRows = max;
}
public void setQueryTimeout(int seconds) {}
//== end methods of interface Statement
protected void finalize() {
close();
}
/**
* Adds a warning to the pile of warnings this Statement object has. If
* there were no warnings (or clearWarnings was called) this warning will
* be the first, otherwise this warning will get appended to the current
* warning.
*
* @param reason the warning message
*/
private void addWarning(String reason) {
if (warnings == null) {
warnings = new SQLWarning(reason);
} else {
warnings.setNextWarning(new SQLWarning(reason));
}
}
/**
* The CacheThread represents a pseudo array holding all results. For real
* only a part of the complete result set is cached, but upon request for
* a result outside the actual cache, the cache is shuffled so the result
* comes available.
*/
class CacheThread extends Thread {
/** the last error messages */
private String error;
/** A queue of queries that need to be executed by this Statement */
private List queryQueue = new LinkedList();
/** The state WAIT represents this thread to be waiting for something to do */
private final static int WAIT = 0;
/** The state QUERY represents this thread to be executing a query */
private final static int QUERY = 1;
/** The state DEAD represents this thread to be dead and unable to do anything */
private final static int DEAD = 2;
/** Whether this CacheThread is still running, executing or waiting */
private int state = WAIT;
public void run() {
while(state != DEAD) {
Object cur;
synchronized(queryQueue) {
cur = null;
if (queryQueue.size() == 0) {
try {
state = WAIT;
queryQueue.wait();
} catch (InterruptedException e) {
// possible shutdown of this thread?
// next condition check will act appropriately
}
continue;
} else {
cur = queryQueue.remove(0);
}
}
// at this point we have a valid cur, since the wait continues
// and skips this part
if (cur instanceof HeaderList) {
processQuery((HeaderList)cur);
} else if (cur instanceof RawResults) {
fetchBlock((RawResults)cur);
}
}
}
/**
* Lets this thread terminate (die) so it turns into a normal object and
* can be garbage collected.
* A call to this function should be made when the parent Statement
* closes to let this thread disappear.
*/
void shutdown() {
state = DEAD;
// if the thread is blocking on a wait, break it out
synchronized(queryQueue) {
queryQueue.notify();
}
}
/**
* Returns whether an error has occurred since the last call to
* getError() or not
*
* @return true if an error has occured
* @see #getError()
*/
synchronized boolean hasError() {
return(error == null ? false : true);
}
/**
* Returns the last error since the last call to this function. On each
* call to this method the error message is cleared.
*
* @return the last error message
*/
synchronized String getError() {
String ret = error;
error = null;
return(ret);
}
HeaderList addQuery(String query) throws IllegalStateException {
if (state == DEAD) throw
new IllegalStateException("CacheThread shutting down or not running");
HeaderList hdrl;
synchronized(queryQueue) {
hdrl = new HeaderList(query);
queryQueue.add(hdrl);
queryQueue.notify();
}
return(hdrl);
}
RawResults addBlock(Header hdr, int block) throws IllegalStateException {
if (state == DEAD) throw
new IllegalStateException("CacheThread shutting down or not running");
RawResults rawr;
synchronized(queryQueue) {
int cacheSize = hdr.getCacheSize();
// get number of results to fetch
int size = Math.min(cacheSize, hdr.getTupleCount() - (block * cacheSize));
if (size == 0) throw
new IllegalStateException("Should not fetch empty block!");
rawr = new RawResults(size,
"Xexport " + hdr.getID() + " " + block * cacheSize + " " + size);
queryQueue.add(rawr);
queryQueue.notify();
}
return(rawr);
}
void closeResult(int id) throws IllegalStateException {
if (state == DEAD) throw
new IllegalStateException("CacheThread shutting down or not running");
synchronized(queryQueue) {
queryQueue.add(0, new RawResults(0, "Xclose " + id));
queryQueue.notify();
}
}
/**
* Executes the query contained in the given HeaderList, and stores the
* Headers resulting from this query in the HeaderList.
*
* @param hdrl a HeaderList which contains the query to execute
*/
private void processQuery(HeaderList hdrl) {
// copy a few vars, so we are sure they don't change for this query
/** A local copy of fetchSize, so its protected from changes made by
* the Statement parent */
int cacheSize = fetchSize;
/** A local copy of resultSetType, so its protected from changes made
* by the Statement parent */
int rstype = resultSetType;
synchronized (monet) {
try {
// make sure we're ready to send query; read data till we have the
// prompt it is possible (and most likely) that we already have
// the prompt and do not have to skip any lines. Ignore errors from
// previous result sets.
monet.waitForPrompt();
// set the reply size for this query. If it is set to 0 we get a
// prompt after the server sent it's header
try {
((MonetConnection)connection).setReplySize(
maxRows != 0 ? Math.min(maxRows, cacheSize) : cacheSize);
} catch (SQLException e) {
hdrl.addError(e.getMessage());
hdrl.setComplete();
return;
}
// send the query
monet.writeln(hdrl.getQuery());
// go for new results
String tmpLine;
Header hdr = null;
RawResults rawr = null;
int lastState = MonetSocket.EMPTY;
do {
tmpLine = monet.readLine();
if (monet.getLineType() == MonetSocket.ERROR) {
// store the error message in the Header object
hdrl.addError(tmpLine.substring(1));
} else if (monet.getLineType() == MonetSocket.HEADER) {
if (hdr == null) {
hdr = new Header(this, cacheSize, rstype);
rawr = null;
}
hdr.addHeader(tmpLine);
} else if (monet.getLineType() == MonetSocket.RESULT) {
// complete the header info and add to list
if (lastState == MonetSocket.HEADER) {
hdr.complete();
rawr = new RawResults(Math.min(cacheSize, hdr.getTupleCount()), null);
hdr.addRawResults(0, rawr);
// a RawResults must be in hdr at this point!!!
hdrl.addHeader(hdr);
hdr = null;
}
rawr.addRow(tmpLine);
} else if (monet.getLineType() == MonetSocket.EMPTY) {
// empty, will mean Monet stopped somehow (crash?)
hdrl.addError("Unknown linetype: " + tmpLine);
}
} while ((lastState = monet.getLineType()) != MonetSocket.PROMPT1);
// catch resultless headers
if (hdr != null) {
hdr.complete();
hdrl.addHeader(hdr);
}
} catch (SQLException e) {
hdrl.addError(e.getMessage());
// if Monet sent us an incomplete or malformed header, we have
// big problems, thus discard the whole bunch and quit processing
// this one
try {
monet.waitForPrompt();
} catch (IOException ioe) {
hdrl.addError(e.toString());
}
} catch (IOException e) {
hdrl.addError(e.getMessage() + " (Mserver still alive?)");
}
// close the header list, no more headers will follow
hdrl.setComplete();
}
}
/**
* Retrieves a continuation block of a previously (partly) fetched
* result. The data is stored in the given RawResults which also
* holds the Xeport query to issue on the server.
*
* @param rawr a RawResults containing the Xexport to execute
*/
private void fetchBlock(RawResults rawr) {
synchronized (monet) {
try {
// make sure we're ready to send query; read data till we have the
// prompt it is possible (and most likely) that we already have
// the prompt and do not have to skip any lines. Ignore errors from
// previous result sets.
monet.waitForPrompt();
// send the query
monet.writeln(rawr.getXexport());
// go for new results, everything should be result (or error :( )
String tmpLine;
do {
tmpLine = monet.readLine();
if (monet.getLineType() == MonetSocket.RESULT) {
rawr.addRow(tmpLine);
} else if (monet.getLineType() == MonetSocket.ERROR) {
rawr.addError(tmpLine.substring(1));
} else if (monet.getLineType() == MonetSocket.HEADER) {
rawr.addError("Unexpected header found");
} else if (monet.getLineType() == MonetSocket.EMPTY) {
rawr.addError("Unexpected end of stream, Mserver still alive?");
}
} while (monet.getLineType() != MonetSocket.PROMPT1);
} catch (IOException e) {
rawr.addError(e.toString());
}
}
}
}
/**
* Inner class which holds the raw data as read from the server, and
* the associated header information, in a parsed manor, ready for easy
* retrieval.
* <br /><br />
* This object is not intended to be queried by multiple threads
* synchronously. It is designed to work for one thread retrieving rows
* from it. When multiple threads will retrieve rows from this object, it
* is likely for some threads to get locked forever.
*/
class RawResults {
/** The String array to keep the data in */
private String[] data;
/** The Xexport query that results in this block */
private String export;
/** The counter which keeps the current position in the data array */
private int pos;
/** The line to watch for and notify upon when added */
private int watch;
/** The errors generated for this ResultBlock */
private String error;
/**
* Constructs a RawResults object
* @param size the size of the data array to create
*/
public RawResults(int size, String export) {
pos = -1;
data = new String[size];
// a newly set watch will always be smaller than size
watch = data.length;
this.export = export;
error = "";
}
/**
* addRow adds a String of data to this object's data array.
* Note that an IndexOutOfBoundsException can be thrown when an
* attempt is made to add more than the original construction size
* specified.
*
* @param line the String of data to add
*/
public synchronized void addRow(String line) {
data[++pos] = line;
if (pos >= watch) {
// reset the watch
watch = data.length;
// notify listener for our lock object; we got it!
this.notify();
}
}
public synchronized String getRow(int line) throws IllegalArgumentException, SQLException {
if (error != "") throw new SQLException(error);
if (line >= data.length || line < 0)
throw new IllegalArgumentException("Cannot get row outside data range (" + line + ")");
while (setWatch(line)) {
try {
this.wait();
} catch (InterruptedException e) {
// recheck if we got the desired row
}
}
return(data[line]);
}
/**
* Returns the Xexport query associated with this RawResults block.
*
* @return the Xexport query
*/
public String getXexport() {
return(export);
}
/**
* Adds an error to this object's error queue
*
* @param error the error string to add
*/
public void addError(String error) {
this.error += error + "\n";
}
/**
* Sets a watch for a certain row. When the row gets added, a notify
* will be performed on this object itself. The behaviour of this method
* is that it returns whether the row is already in the cache or not, so
* it can for example be used as:
* <pre>
* while (rawr.setWatch(row)) {
* try {
* rawr.wait();
* } catch (InterruptedException e) {
* // recheck if we got the desired row
* }
* }
* rawr.getLine(row);
* </pre>
*
* @param line the row to set the watch for
* @return true when the watch was set, false when the row is already
* fetched and no need for wait/notify is there
*/
private synchronized boolean setWatch(int line) {
boolean ret;
if (line <= pos) {
ret = false;
} else {
watch = line;
ret = true;
}
return(ret);
}
}
/**
* A Header represents a Mapi SQL header which looks like:
*
* <pre>
* # name, value # name
* # varchar, varchar # type
* # 28, # tuplecount
* # 1, # id
* </pre>
*
* This class does not check all arguments for null, size, etc. for
* performance sake!
*/
class Header {
/** The names of the columns in this result */
private String[] name;
/** The types of the columns in this result */
private String[] type;
/** The number of rows this result has */
private int tuplecount;
/** The table ID of this result */
private int id;
/** A Map of result blocks (chunks of size fetchSize/cacheSize) */
private Map resultBlocks;
/** A bitmap telling whether the headers are set or not */
private boolean[] isSet;
/** Whether this Header is closed */
private boolean closed;
/** The CacheThread that we should use when requesting a new block */
private CacheThread cachethread;
// copy a few vars, so we are sure they don't change for this object
/** A local copy of fetchSize, so its protected from changes made by
* the Statement parent */
private int cacheSize;
/** A local copy of resultSetType, so its protected from changes made
* by the Statement parent */
private int rstype;
/** a regular expression that we often use to split
* the headers into an array (compile them once) */
private final Pattern splitPattern = Pattern.compile(",\t");
/**
* Sole constructor, which requires a CacheThread parent to be given.
*
* @param parent the CacheThread that created this Header and will
* supply new result blocks
* @param cs the cache size to use
* @param rst the ResultSet type to use
*/
public Header(CacheThread parent, int cs, int rst) {
isSet = new boolean[4];
resultBlocks = new HashMap();
cachethread = parent;
cacheSize = cs;
rstype = rst;
closed = false;
}
/**
* Parses the given string and changes the value of the matching
* header appropriately.
*
* @param tmpLine the string that contains the header
* @throws SQLException if the header cannot be parsed or is unknown
*/
public void addHeader(String tmpLine) throws SQLException {
int pos = tmpLine.lastIndexOf("
if (pos == -1) {
throw new SQLException("Illegal header: " + tmpLine);
}
// split the header line into an array
String[] values =
splitPattern.split(tmpLine.substring(1, pos - 1));
// remove whitespace from all the results
for (int i = 0; i < values.length; i++) {
values[i] = values[i].trim();
}
// add the header
String name = tmpLine.substring(pos + 1).trim();
if (name.equals("name")) {
setNames(values);
} else if (name.equals("type")) {
setTypes(values);
} else if (name.equals("tuplecount")) {
setTupleCount(values[0]);
} else if (name.equals("id")) {
setID(values[0]);
} else {
throw new SQLException("Unknown header: " + name);
}
}
/**
* Sets the name header and updates the bitmask
*
* @param name an array of Strings holding the column names
*/
private void setNames(String[] name) {
this.name = name;
isSet[0] = true;
}
/**
* Sets the type header and updates the bitmask
*
* @param type an array of Strings holding the column types
*/
private void setTypes(String[] type) {
this.type = type;
isSet[1] = true;
}
/**
* Sets the tuplecount header and updates the bitmask
*
* @param tuplecount a string representing the tuple count of
* this result
* @throws SQLException if the given string is not a parseable
* number
*/
private void setTupleCount(String tuplecount) throws SQLException {
try {
this.tuplecount = Integer.parseInt(tuplecount);
} catch (NumberFormatException e) {
throw new SQLException("tuplecount " + tuplecount + " is not a number!");
}
isSet[2] = true;
}
/**
* Sets the id header and updates the bitmask
*
* @param id a string representing the table id of
* this result
* @throws SQLException if the given string is not a parseable
* number
*/
private void setID(String id) throws SQLException {
try {
this.id = Integer.parseInt(id);
} catch (NumberFormatException e) {
throw new SQLException("ID " + id + " is not a number!");
}
isSet[3] = true;
}
/**
* Adds the given RawResults to this Header at the given block
* position.
*
* @param block the result block the RawResults object represents
* @param rawr the RawResults to add
*/
public void addRawResults(int block, RawResults rr) {
resultBlocks.put("" + block, rr);
}
/**
* Marks this Header as being completed. A complete Header needs
* to be consistant with regards to its internal data.
*
* @throws SQLException if the data currently in this Header is not
* sufficient to be consistant
*/
public void complete() throws SQLException {
boolean hasSome = isSet[0] || isSet[1] || isSet[2] || isSet[3];
if (hasSome) {
String error = "";
if (!isSet[0]) error += "name header missing\n";
if (!isSet[1]) error += "type header missing\n";
if (!isSet[2]) error += "tuplecount header missing\n";
if (!isSet[3]) error += "id header missing\n";
if (!(isSet[0] && isSet[1] && isSet[2] && isSet[3]))
throw new SQLException(error);
if (maxRows != 0)
tuplecount = Math.min(tuplecount, maxRows);
// make sure the cache size is minimal to
// reduce overhead and memory usage
cacheSize = Math.min(tuplecount, cacheSize);
} else {
// a no header query (sigh, yes that can happen)
// make sure there is NO RawResults
resultBlocks.clear();
}
}
/**
* Returns the names of the columns
*
* @return the names of the columns
*/
public String[] getNames() {
return(name);
}
/**
* Returns the types of the columns
*
* @return the types of the columns
*/
public String[] getTypes() {
return(type);
}
/**
* Returns the number of results for this result
*
* @return the number of results for this result
*/
public int getTupleCount() {
return(tuplecount);
}
/**
* Returns the table id for this result
*
* @return the table id for this result
*/
public int getID() {
return(id);
}
/**
* Returns the cache size used within this Header
*
* @return the cache size
*/
public int getCacheSize() {
return(cacheSize);
}
/**
* Returns a line from the cache. If the line is already present in the
* cache, it is returned, if not apropriate actions are taken to make
* sure the right block is being fetched and as soon as the requested
* line is fetched it is returned.
*
* @param row the row in the result set to return
* @return the exact row read as requested or null if the requested row
* is out of the scope of the result set
* @throws SQLException if an database error occurs
*/
String getLine(int row) throws SQLException {
if (row >= tuplecount || row < 0) return null;
int block = row / cacheSize;
int blockLine = row % cacheSize;
// do we have the right block (still) loaded?
RawResults rawr;
synchronized(resultBlocks) {
rawr = (RawResults)(resultBlocks.get("" + block));
if (rawr == null) {
// if we're running forward only, we can discard the old
// block loaded
if (rstype == ResultSet.TYPE_FORWARD_ONLY) {
resultBlocks.clear();
}
/// todo: ponder about a maximum number of blocks to keep
/// in memory when dealing with random access to
/// reduce memory blow-up
// ok, need to fetch cache block first
rawr = cachethread.addBlock(this, block);
resultBlocks.put("" + block, rawr);
}
}
try {
return(rawr.getRow(blockLine));
} catch (IllegalArgumentException e) {
throw new SQLException(e.getMessage());
}
}
/**
* Closes this Header by sending an Xclose to the server indicating
* that the result can be closed at the server side as well.
*/
public void close() {
if (closed) return;
try {
// send command to server indicating we're done with this
// result only if we had an ID in the header... Currently
// on updates, inserts and deletes there is no header at all
if (isSet[3]) {
// since it is not really critical `when' this command is
// executed, we put it on the CacheThread's queue. If we
// would want to do it ourselves here, a deadlock situation
// may occur if the HeaderList calls us.
cachethread.closeResult(id);
}
} catch (IllegalStateException e) {
// too late, cache thread is gone or shutting down
}
closed = true;
}
/**
* Returns whether this Header is closed
*
* @return whether this Header is closed
*/
public boolean isClosed() {
return(closed);
}
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
/**
* A list of Header objects. Headers are added to this list till the
* setComplete() method is called. This allows users of this HeaderList
* to determine whether more Headers can be added or not. Upon add or
* completion, the object itself is notified, so a user can use this object
* to wait on when figuring out whether a new Header is available.
*/
private class HeaderList {
/** The query that resulted in this HeaderList */
private String query;
/** Whether there are more Headers to come or not */
private boolean complete;
/** A list of the Headers associated with the query, in the right order */
private List headers;
/** The current header returned by getNextHeader() */
private int curHeader;
/** The errors produced by the query */
private String error;
/**
* Main constructor.
*
* @param query the query that is the 'cause' of this HeaderList
*/
public HeaderList(String query) {
this.query = query;
complete = false;
headers = new ArrayList();
curHeader = 0;
error = "";
}
/** Sets the complete flag to true and notifies this object. */
public synchronized void setComplete() {
complete = true;
this.notify();
}
/** Adds a Header to this object and notifies this object. */
public synchronized void addHeader(Header header) {
headers.add(header);
this.notify();
}
/**
* Retrieves the query that was executed and resulted in this
* HeaderList.
*
* @return the query
*/
public String getQuery() {
return(query);
}
/**
* Retrieves the number of Headers currently in this list.
*
* @return the number of Header objects in this list
*/
public synchronized int getSize() {
return(headers.size());
}
/**
* Returns whether this HeaderList is completed.
*
* @return whether this HeaderList is completed
*/
public synchronized boolean isCompleted() {
return(complete);
}
/**
* Retrieves the requested Header.
*
* @return the Header in this list at position i
*/
public synchronized Header getHeader(int i) {
return((Header)(headers.get(i)));
}
/**
* Retrieves the next available header, or null if there are no next
* headers to come.
*
* @return the next Header available or null
*/
public synchronized Header getNextHeader() throws SQLException {
if (error != "") throw new SQLException(error);
while(curHeader >= getSize() && !isCompleted()) {
try {
this.wait();
} catch (InterruptedException e) {
// hmmm... recheck to see why we were woken up
}
}
if (curHeader >= getSize()) {
// header is obviously completed so, there are no more headers
return(null);
} else {
// return this header, and increment the counter
return(getHeader(curHeader++));
}
}
/** Adds an error to the pile of errors for this object */
public synchronized void addError(String error) {
this.error += error + "\n";
}
/**
* Closes this HeaderList by closing all the Headers in this
* HeaderList.
*/
public synchronized void close() {
for (int i = 0; i < headers.size(); i++) {
getHeader(i).close();
}
}
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
}
|
package chessGame;
import java.util.ArrayList;
public class ChessMonitoringSystem {
//private static ChessPiece[] allChessPieces;
private static ArrayList<ChessPiece> allChessPieces;
private static ChessMonitoringSystem instance;
private ChessMonitoringSystem() {
// TODO - implement ChessMonitoringSystem.ChessMonitoringSystem
// throw new UnsupportedOperationException();
}
public static ChessMonitoringSystem getInstance() {
if (instance==null)
instance = new ChessMonitoringSystem();
return instance;
}
public void initializeChessBoard() {
// TODO - implement ChessMonitoringSystem.initializeChessboard
throw new UnsupportedOperationException();
}
public void initializeChessPieces(ChessPlayer player1, ChessPlayer player2) {
// TODO - implement ChessMonitoringSystem.initializeChessPieces
//allChessPieces = new ChessPiece[32];
allChessPieces=new ArrayList<>();
ChessPlayer[] chessPlayerList = {player1, player2};
int allChessYPos = 1;
int pawnYPos = 2;
for (int i = 0; i<2; i++)
{
// allChessPieces[i*16] = new Rook(chessPlayerList[i], "a"+allChessYPos);
// allChessPieces[i*16+1] = new Knight(chessPlayerList[i], "b"+allChessYPos);
// allChessPieces[i*16+2] = new Bishop(chessPlayerList[i], "c"+allChessYPos);
// allChessPieces[i*16+3] = new King(chessPlayerList[i], "d"+allChessYPos);
// allChessPieces[i*16+4] = new Queen(chessPlayerList[i], "e"+allChessYPos);
// allChessPieces[i*16+5] = new Bishop(chessPlayerList[i], "f"+allChessYPos);
// allChessPieces[i*16+6] = new Knight(chessPlayerList[i], "g"+allChessYPos);
// allChessPieces[i*16+7] = new Rook(chessPlayerList[i], "h"+allChessYPos);
allChessPieces.add(new Rook(chessPlayerList[i], "a"+allChessYPos));
allChessPieces.add(new Knight(chessPlayerList[i], "b"+allChessYPos));
allChessPieces.add(new Bishop(chessPlayerList[i], "c"+allChessYPos));
allChessPieces.add(new King(chessPlayerList[i], "d"+allChessYPos));
allChessPieces.add(new Queen(chessPlayerList[i], "e"+allChessYPos));
allChessPieces.add(new Bishop(chessPlayerList[i], "f"+allChessYPos));
allChessPieces.add(new Knight(chessPlayerList[i], "g"+allChessYPos));
allChessPieces.add(new Rook(chessPlayerList[i], "h"+allChessYPos));
//8 pawns
int xPosCharCode = 97;
for (int j = 0; j<8; j++)
{
String pawnXPos= ""+(char)xPosCharCode; //x-coordinate of pawns' position
//allChessPieces[i*16+8+j] = new Pawn(chessPlayerList[i], pawnXPos+pawnYPos);
allChessPieces.add(new Pawn(chessPlayerList[i], pawnXPos+pawnYPos));
xPosCharCode++;
}
pawnYPos = 7; //inverted y-coordinate for Pawns
allChessYPos = 8; //invert y-coordinate for oponent's chess pieces
}
// throw new UnsupportedOperationException();
}
public void showAllChessPiecesPosition() {
// TODO - implement ChessMonitoringSystem.showAllChessPiecesPosition
String [][] chessPiecesPosition = new String[8][8]; //virtual chess board
String tempPos = null;
int xPosInNum = 0;
int yPosInNum = 0;
//initialize chess board
for (int i = 0; i<8; i++)
for (int j = 0; j<8; j++)
chessPiecesPosition[i][j] = "O"; //or "\u25A1", a white square
for (ChessPiece c: allChessPieces)
{
tempPos = c.getPosition();
if (tempPos==null)
chessPiecesPosition[yPosInNum-1][xPosInNum-1]="O";
else
{
xPosInNum = tempPos.charAt(0)-96;
yPosInNum = tempPos.charAt(1)-48;
}
chessPiecesPosition[yPosInNum-1][xPosInNum-1] = c.toString(); //a1 on chess board->[0][0] in array
}
System.out.println(String.format("%3s%2s%2s%2s%2s%2s%2s%2s","a", "b", "c", "d", "e", "f", "g", "h"));
for (int i = 0; i<8; i++)
{
System.out.print((8-i)+" ");
for (int j = 0; j<8; j++)
{
System.out.print(chessPiecesPosition[8-i-1][j]+" "); //yPos: 8,7,6,...->7,6,5,...
//xPos: a,b,c,...->0,1,2,...
}
System.out.println(8-i);
}
System.out.println(String.format("%3s%2s%2s%2s%2s%2s%2s%2s","a", "b", "c", "d", "e", "f", "g", "h"));
// throw new UnsupportedOperationException();
}
public boolean moveChessPiece(ChessPlayer player,String oldPos,String newPos) {
boolean validMove=true;
ChessPiece movingChess = getChessPiece(oldPos);
/*ERROR-CATCHING : MAY CHANGE TO TRY-CATCH CLAUSE*/
if(movingChess == null)
System.out.println("Chesspiece not found!");
else if(movingChess.getPlayer()!=player){
System.out.println("Selected piece does not belong to you!");
validMove=false;
}
else if(movingChess.moveIsAvailable(newPos)) {
if(getChessPiece(newPos)!=null) {
player.addScore(getChessPiece(newPos).getScore());
removeChessPiece(newPos);
}
movingChess.updatePosition(newPos);
}
else{
System.out.println("The move is invalid.");
validMove=false;
}
return validMove;
// throw new UnsupportedOperationException();
}
public ChessPiece getChessPiece(String position){
String tempChessPos = null;
for (ChessPiece c: allChessPieces)
{
tempChessPos = c.getPosition();
if (tempChessPos.equals(position))
return c;
}
return null;
}
/*Stub
private boolean isChessPieceCaptured(ChessPiece origin,String position) {
// TODO - implement ChessMonitoringSystem.chessPieceIsCaptured
ChessPiece target = getChessPiece(position);
if(origin.getPlayer()!=target.getPlayer())
return true;
else
return false;
}
*/
private void removeChessPiece(String position) {
// TODO - implement ChessMonitoringSystem.removeChessPiece
ChessPiece target = getChessPiece(position);
if(target instanceof King) {
ChessPlayer winner = target.getPlayer();
}
//target.updatePosition(null);
allChessPieces.remove(target); //IF USE ARRAYLIST
checkGameResult(winner);
}
public void checkGameResult(ChessPlayer winner) {
// TODO - Possible Gamemode conditions
//if(getGameMode());
System.out.printf("Player %s won!", winner.toString());
}
public boolean isKingCaptured() {
// TODO Auto-generated method stub
return false;
}
public void getGameResult(int mode) {
// TODO Auto-generated method stub
//player.getPlayerScore()
//player.getPlayerName()
}
}
|
package jodd.io.http;
import jodd.io.StreamUtil;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Simple HTTP tunnel base ready to be extended.
*/
public class HttpTunnel {
/**
* The number of threads that can be executed in parallel.
*/
protected int threadPoolSize = 10;
/**
* Number of incoming sockets connection that can be hold
* before processing each.
*/
protected int socketBacklog = 100;
/**
* Tunnel listening port.
*/
protected int listenPort = 8888;
/**
* Target host.
*/
protected String targetHost = "localhost";
/**
* Target port.
*/
protected int targetPort = 8080;
protected ExecutorService executorService;
protected boolean running;
protected ServerSocket serverSocket;
/**
* Starts HTTP tunnel. Method ends when the tunnel is stopped.
*/
public void start() throws IOException {
serverSocket = new ServerSocket(listenPort, socketBacklog);
serverSocket.setReuseAddress(true);
executorService = Executors.newFixedThreadPool(threadPoolSize);
running = true;
while (running) {
Socket socket = serverSocket.accept();
socket.setKeepAlive(false);
executorService.execute(onSocketConnection(socket));
}
executorService.shutdown();
}
/**
* Invoked on incoming connection. By default returns {@link HttpTunnelConnection}
* to handle the connection. May be used to return custom
* handlers.
*/
protected Runnable onSocketConnection(Socket socket) {
return new HttpTunnelConnection(socket);
}
/**
* Stops the tunnel, shutdowns the thread pool and closes server socket.
*/
public void stop() {
running = false;
executorService.shutdown();
try {
serverSocket.close();
} catch (IOException ignore) {
}
}
/**
* Single connection handler that performs the tunneling.
*/
public class HttpTunnelConnection implements Runnable {
protected final Socket socket;
public HttpTunnelConnection(Socket socket) {
this.socket = socket;
}
public void run() {
try {
tunnel();
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
/**
* Invoked after income connection is parsed.
* The only thing changed is the modified "Host" header
* to match the target.
*/
protected void onRequest(HttpTransfer request) {
}
/**
* Invoked after target response is processed. Response is now
* ready to be sent back to the client. The following header
* parameters are changed:
* <li>Transfer-Encoding is removed, as body is returned at once,
* <li>Content-Length is added/update to body size.
*/
protected void onResponse(HttpTransfer response) {
}
/**
* Performs the tunneling. The following steps occurs:
* <li>read and parse clients request
* <li>open socket to target
* <li>fix request and resend it to target
* <li>read targets response
* <li>fix response and resend it to client
*/
protected void tunnel() throws IOException {
// read request
InputStream socketInput = socket.getInputStream();
HttpTransfer request = Http.readRequest(socketInput);
// open client socket to target
Socket clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress(targetHost, targetPort));
// fix request
request.addHeader("Host", targetHost);
onRequest(request);
// resend request to target
OutputStream out = clientSocket.getOutputStream();
request.send(out);
// read target response
InputStream in = clientSocket.getInputStream();
HttpTransfer response = Http.readResponse(in);
// close client socket
StreamUtil.close(in);
StreamUtil.close(out);
clientSocket.close();
// fix response
if (response.getBody() != null) {
response.removeHeader("Transfer-Encoding");
response.addHeader("Content-Length", response.getBody().length);
}
onResponse(response);
// send response back
OutputStream socketOutput = socket.getOutputStream();
response.send(socketOutput);
// close socket
StreamUtil.close(socketInput);
StreamUtil.close(socketOutput);
socket.close();
}
}
}
|
package com.polydes.common.sys;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.log4j.Logger;
import com.polydes.common.nodes.HierarchyModel;
import stencyl.core.lib.Game;
import stencyl.sw.SW;
import stencyl.sw.util.FileHelper;
import stencyl.sw.util.Locations;
public class FileMonitor
{
private static final Logger log = Logger.getLogger(FileMonitor.class);
public static final int POLLING_INTERVAL = 5 * 1000;
private static FileAlterationObserver observer;
private static FileAlterationMonitor monitor;
private static FileAlterationListener listener;
public static HashMap<String, SysFile> fileCache = new HashMap<String, SysFile>();
private static HierarchyModel<SysFile,SysFolder> model;
public static HierarchyModel<SysFile,SysFolder> getExtrasModel()
{
if(model == null)
{
File extrasDir = new File(Locations.getGameLocation(Game.getGame()), "extras");
if(!extrasDir.exists())
extrasDir.mkdir();
model = new HierarchyModel<SysFile, SysFolder>(registerOnRoot(extrasDir), SysFile.class, SysFolder.class)
{
@Override
public void massMove(List<SysFile> transferItems, SysFolder target, int position)
{
List<File> toMove = new ArrayList<File>();
for(SysFile item : transferItems)
if(item.getParent() != target)
toMove.add(item.getFile());
if(toMove.isEmpty())
return;
SysFileOperations.moveFiles(toMove, target.getFile());
};
@Override
public void removeItem(SysFile item, SysFolder target)
{
FileHelper.delete(item.getFile());
FileMonitor.refresh();
}
};
}
return model;
}
public static SysFolder registerOnRoot(File folder)
{
if(!folder.exists())
{
log.error("Couldn't begin file watcher, directory does not exist:\n" + folder.getAbsolutePath());
return null;
}
if(observer != null)
{
unregister();
}
observer = new FileAlterationObserver(folder);
monitor = new FileAlterationMonitor(POLLING_INTERVAL);
listener = new FileAlterationListenerAdaptor()
{
@Override
public void onFileCreate(File file)
{
log.info("File created: " + file.getAbsolutePath());
SysFile sysFile = getSysFile(file);
SysFolder parent = getParentSysFolder(file);
parent.addItem(sysFile, parent.findInsertionIndex(sysFile.getName(), false));
}
@Override
public void onFileDelete(File file)
{
log.info("File deleted: " + file.getAbsolutePath());
SysFile toRemove = getSysFile(file);
if(toRemove != null && toRemove.getParent() != null)
{
model.getSelection().remove(toRemove);
toRemove.getParent().removeItem(toRemove);
}
dispose(file);
}
@Override
public void onFileChange(File file)
{
log.info("File changed: " + file.getAbsolutePath());
getSysFile(file).notifyChanged();
}
@Override
public void onDirectoryCreate(File directory)
{
log.info("Folder created: " + directory.getAbsolutePath());
SysFile sysFile = getSysFile(directory);
SysFolder parent = getParentSysFolder(directory);
//Ignore owned directories.
if(parent == model.getRootBranch() && extensionExists(directory.getName()))
return;
parent.addItem(sysFile, parent.findInsertionIndex(sysFile.getName(), true));
}
@Override
public void onDirectoryDelete(File directory)
{
log.info("Folder deleted: " + directory.getAbsolutePath());
SysFile toRemove = getSysFile(directory);
SysFolder parent = getParentSysFolder(directory);
//Ignore owned directories.
if(parent == model.getRootBranch() && extensionExists(directory.getName()))
return;
model.getSelection().remove(toRemove);
toRemove.getParent().removeItem(toRemove);
dispose(directory);
}
@Override
public void onDirectoryChange(File directory)
{
log.info("Folder changed: " + directory.getAbsolutePath());
}
};
observer.addListener(listener);
monitor.addObserver(observer);
try
{
monitor.start();
}
catch (Exception e)
{
e.printStackTrace();
}
SysFolder toReturn = (SysFolder) getSys(folder);
readFolder(toReturn, true);
return toReturn;
}
private static SysFile getSys(File file)
{
String key = file.getAbsolutePath();
if(fileCache.containsKey(key))
return fileCache.get(key);
if(!file.exists())
return null;
SysFile newFile;
if(file.isDirectory())
newFile = new SysFolder(file);
else
newFile = new SysFile(file);
fileCache.put(key, newFile);
return newFile;
}
private static void dispose(File file)
{
fileCache.remove(file.getAbsolutePath());
}
//TODO: This could run unnecessarily slow for large filesets.
private static void readFolder(SysFolder folder, boolean isRoot)
{
for(File file : folder.getFile().listFiles())
{
if(isRoot && extensionExists(file.getName()))
continue;
SysFile sysFile = getSys(file);
folder.addItem(sysFile, folder.findInsertionIndex(sysFile.getName(), sysFile instanceof SysFolder));
if(file.isDirectory())
readFolder((SysFolder) sysFile, false);
}
}
private static boolean extensionExists(String name)
{
return SW.get().getExtensionManager().getExtensions().containsKey(name);
}
private static SysFile getSysFile(File file)
{
return getSys(file);
}
private static SysFolder getParentSysFolder(File file)
{
return (SysFolder) getSys(file.getParentFile());
}
public static void refresh()
{
observer.checkAndNotify();
}
public static void unregister()
{
try
{
monitor.stop(1);
monitor.removeObserver(observer);
observer.removeListener(listener);
monitor = null;
observer = null;
listener = null;
}
catch (Exception e)
{
e.printStackTrace();
}
fileCache.clear();
}
}
|
package polytheque.model.pojos;
import java.sql.Date;
public class Adherent {
private int idAdherent;
private String nom;
private String prenom;
private Date dateNaissance;
private String rue;
private int cp;
private String ville;
private String mail;
private int telephone;
private String pseudo;
private String mdp;
private boolean estAJour;
private boolean peutEmprunter;
private int cptRetard;
public Adherent(String nom, String prenom, Date dateNaissance, String adresse, int cp, String ville,
String mail, int tel, String pseudo, String mdp){
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.rue = adresse;
this.cp = cp;
this.ville = ville;
this.mail = mail;
this.pseudo = pseudo;
this.mdp = mdp;
this.estAJour = true;
this.peutEmprunter = true;
this.cptRetard = 0;
}
public Adherent(int id, String nom, String prenom, Date dateNaissance, String adresse, int cp, String ville,
String mail, int tel, String pseudo, String mdp, boolean estAJour, boolean peutEmprunter, int nbRetards){
this.idAdherent = id;
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.rue = adresse;
this.cp = cp;
this.ville = ville;
this.mail = mail;
this.pseudo = pseudo;
this.mdp = mdp;
this.estAJour = estAJour;
this.peutEmprunter = peutEmprunter;
this.cptRetard = nbRetards;
}
/**
* Obtenir le nom de l'adherent
*
* @return Le nom de l'adherent
*/
public String getNom() {
return this.nom;
}
/**
* Modifier le nom de l'adherent
* Utilisable uniquement par un administrateur
*
* @param nom
* le nom de l'adherent
*/
public void setNom(String nom) {
this.nom = nom;
}
/**
* Obtenir le prenom de l'adherent
*
* @return le prenom de l'adherent
*/
public String getPrenom() {
return this.prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getRue() {
return this.rue;
}
public void setRue(String rue) {
this.rue = rue;
}
public int getCP() {
return this.cp;
}
public void setCP(int cp) {
this.cp = cp;
}
public String getVille() {
return this.ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getTelephone() {
return this.telephone;
}
public void setTelephone(int telephone) {
this.telephone = telephone;
}
public String getPseudo() {
return this.pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getMdp() {
return this.mdp;
}
public void setMdp(String mdp) {
this.mdp = mdp;
}
public boolean isEstAJour() {
return this.estAJour;
}
public void setEstAJour(boolean estAJour) {
this.estAJour = estAJour;
}
public boolean peutEmprunter() {
return this.peutEmprunter;
}
public void setPeutEmprunter(boolean peutEmprunter) {
this.peutEmprunter = peutEmprunter;
}
public int getCompteurRetard(){
return this.cptRetard;
}
public void setCompteurRetard(int nbRetards){
this.cptRetard = nbRetards;
}
public void ajoutCompteurRetard(){
this.cptRetard ++;
}
public int getIdAdherent() {
return idAdherent;
}
public void setIdAdherent(int idAdherent) {
this.idAdherent = idAdherent;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
}
|
package com.fatecpg.data;
import br.com.fatecpg.helpers.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class Usuario {
private Integer _id;
private String _nome;
private String _password;
private Integer _perfilId;
//
public Usuario(Integer _id, String _nome, String _password, Integer perfilId) {
this._id = _id;
this._nome = _nome;
this._password = _password;
this._perfilId = perfilId;
}
public Usuario(String _nome, String _password, Integer perfilId) {
this._nome = _nome;
this._password = _password;
this._perfilId = perfilId;
}
// ### GETTERS E SETTERS
public Integer getId() {
return _id;
}
public String getNome() {
return _nome;
}
public void setNome(String _nome) {
this._nome = _nome;
}
private String getPassword() {
return _password;
}
public void setPassword(String _password) {
this._password = _password;
}
public Integer getPerfilId() {
return _perfilId;
}
public void setPerfilId(Integer perfilId) {
this._perfilId = perfilId;
}
public boolean isAdmin(){
return this.getPerfil().getDescricao().equals("admin");
}
//
public boolean store() throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
try (Statement statement = connection.createStatement()) {
String SQL = String.format(
"INSERT INTO USUARIO(NOME, PASSWORD, PERFIL_ID) VALUES('%s', '%s', %d)",
this._nome, this._password, this._perfilId);
statement.execute(SQL, Statement.RETURN_GENERATED_KEYS);
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
this._id = rs.getInt(1);
}
} catch (Exception ex) {
System.out.println("Erro ao recuperar a GeneratedKey: " + ex.getMessage());
}
statement.close();
if (this._id != null) {
return true;
}
} catch (Exception ex) {
System.out.println("Erro ao inserir o Usuário: " + ex.getMessage());
}
connection.close();
} catch (SQLException ex) {
System.out.println("Erro ao conectar ao banco de dados: " + ex.getMessage());
}
return false;
}
public static Usuario find(Integer id) throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
PreparedStatement pstatement = connection.prepareStatement(String.format("SELECT * FROM USUARIO WHERE ID = ?"));
pstatement.setInt(1, id);
try (ResultSet result = pstatement.executeQuery()) {
if (result.next()) {
return new Usuario(
result.getInt("ID"),
result.getString("NOME"),
result.getString("PASSWORD"),
result.getInt("PERFIL_ID")
);
}
} catch (Exception ex) {
System.out.println("Erro ao consultar o Usuário: " + ex.getMessage());
}
connection.close();
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return null;
}
// Retorn todos os registros
public static ArrayList<Usuario> all() throws SQLException {
ArrayList<Usuario> usuarios = new ArrayList<>();
try (Connection connection = ConnectionFactory.getConnection()) {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM USUARIO");
while (result.next()) {
usuarios.add(new Usuario(
result.getInt("ID"),
result.getString("NOME"),
result.getString("PASSWORD"),
result.getInt("PERFIL_ID")
));
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return usuarios;
}
public static ArrayList<Usuario> all(int perfilId) throws SQLException {
ArrayList<Usuario> usuarios = new ArrayList<>();
try (Connection connection = ConnectionFactory.getConnection()) {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM USUARIO WHERE PERFIL_ID = " + perfilId );
while (result.next()) {
usuarios.add(new Usuario(
result.getInt("ID"),
result.getString("NOME"),
result.getString("PASSWORD"),
result.getInt("PERFIL_ID")
));
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return usuarios;
}
public boolean delete() throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
try (PreparedStatement pstatement = connection.prepareStatement("DELETE FROM USUARIO WHERE ID = ?")) {
pstatement.setInt(1, this._id);
pstatement.execute();
} catch (Exception ex) {
System.out.println("Erro ao excluir o Usuário: " + ex.getMessage());
}
connection.close();
if (Alternativa.find(this._id) == null) {
return true;
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return false;
}
//
public Perfil getPerfil() {
try {
return Perfil.find(this._perfilId);
} catch (SQLException ex) {
System.out.println("Erro ao obter Perfil: " + ex.getMessage());
}
return null;
}
}
|
package org.genericsystem.reinforcer.tools;
import java.util.Optional;
public class GSRect {
private double x, y, width, height;
public GSRect(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public GSRect() {
this(0, 0, 0, 0);
}
public GSRect(GSPoint p1, GSPoint p2) {
x = p1.getX() < p2.getX() ? p1.getX() : p2.getX();
y = p1.getY() < p2.getY() ? p1.getY() : p2.getY();
width = (p1.getX() > p2.getX() ? p1.getX() : p2.getX()) - x;
height = (p1.getY() > p2.getY() ? p1.getY() : p2.getY()) - y;
}
public GSRect(GSPoint p, GSSize s) {
this(p.getX(), p.getY(), s.getWidth(), s.getHeight());
}
public GSRect(double[] vals) {
set(vals);
}
private void set(double[] vals) {
if (vals != null) {
x = vals.length > 0 ? vals[0] : 0;
y = vals.length > 1 ? vals[1] : 0;
width = vals.length > 2 ? vals[2] : 0;
height = vals.length > 3 ? vals[3] : 0;
} else {
x = 0;
y = 0;
width = 0;
height = 0;
}
}
@Override
public GSRect clone() {
return new GSRect(x, y, width, height);
}
public GSPoint tl() {
return new GSPoint(x, y);
}
public GSPoint br() {
return new GSPoint(x + width, y + height);
}
public GSSize size() {
return new GSSize(width, height);
}
public double area() {
return width * height;
}
public boolean empty() {
return width <= 0 || height <= 0;
}
/**
* Checks if a {@link GSPoint} is contained in a {@link GSRect} (being inclusive).
*
* @param rect - the rectangle
* @param p - the point
* @return true if <code>p</code> is contained in <code>rect</code>, false otherwise
*/
public boolean contains(GSPoint p) {
return x <= p.getX() && p.getX() <= x + width && y <= p.getY() && p.getY() <= y + height;
}
/**
* Compute the inclusive area between two rectangles (intersection area / union area)
*
* @param rect1 - the first rectangle
* @param rect2 - the second rectangle
* @return the percentage of overlap between the two rectangles, defined by <code>intersection.area() / union.area()</code>
*/
public double inclusiveArea(GSRect rect2) {
Optional<GSRect> optional = getIntersection(rect2);
if (!optional.isPresent())
return 0;
GSRect intersection = optional.get();
GSRect union = getUnion(rect2);
double area = intersection.area() / union.area();
return area;
}
/**
* Compute the intersection of two rectangles.
*
* @param rect1 - the first rectangle
* @param rect2 - the second rectangle
* @return an {@link Optional} with the intersecting {@link GSRect}, or an empty Optional if no intersection was found
*/
public Optional<GSRect> getIntersection(GSRect rect2) {
// First, check whether a rectangle is contained in the other
Optional<GSRect> insider = getInsider(rect2);
if (insider.isPresent())
return insider;
// If not, compute the intersection
double tlX = Math.max(tl().getX(), rect2.tl().getX());
double tlY = Math.max(tl().getY(), rect2.tl().getY());
double brX = Math.min(br().getX(), rect2.br().getX());
double brY = Math.min(br().getY(), rect2.br().getY());
if (brX - tlX <= 0 || brY - tlY <= 0) // XXX: swap tl and br if < 0?
return Optional.empty();
else
return Optional.of(new GSRect(new GSPoint(tlX, tlY), new GSPoint(brX, brY)));
}
/**
* Compute the union of two rectangles.
*
* @param rect1 - the first rectangle
* @param rect2 - the second rectangle
* @return the union {@link GSRect}
*/
public GSRect getUnion(GSRect rect2) {
// First, check whether a rectangle is contained in the other
Optional<GSRect> inside = getInsider(rect2);
if (inside.isPresent()) {
GSRect insider = inside.get();
return insider.equals(this) ? rect2 : this;
}
// If not, compute the union
double tlX = Math.min(tl().getX(), rect2.tl().getX());
double tlY = Math.min(tl().getY(), rect2.tl().getY());
double brX = Math.max(br().getX(), rect2.br().getX());
double brY = Math.max(br().getY(), rect2.br().getY());
return new GSRect(new GSPoint(tlX, tlY), new GSPoint(brX, brY));
}
public boolean isOverlapping(GSRect other) throws IllegalArgumentException {
if (other == null)
throw new IllegalArgumentException("One of the rectangles is null");
return x <= other.br().getX() && other.tl().getX() <= br().getX() && y <= other.br().getY() && other.tl().getY() <= br().getY();
}
/**
* Compare this rectangle with another rectangle, and returns the smaller rectangle if it is inside the other. Returns an empty {@link Optional} if no rectangles is contained in the other.
*
* @param rect2 - the second rectangle
* @return an {@link Optional} with the rectangle contained in the other, an empty Optional if no rectangles is contained in the other.
*/
public Optional<GSRect> getInsider(GSRect rect2) {
GSPoint[] points1 = decomposeClockwise();
GSPoint[] points2 = rect2.decomposeClockwise();
boolean isGSRect2InGSRect1 = true;
boolean isGSRect1InGSRect2 = true;
for (GSPoint p : points2) {
if (!contains(p))
isGSRect2InGSRect1 = false;
}
if (!isGSRect2InGSRect1) {
for (GSPoint p : points1) {
if (!rect2.contains(p))
isGSRect1InGSRect2 = false;
}
if (isGSRect1InGSRect2)
return Optional.of(this);
else
return Optional.empty();
} else {
return Optional.of(rect2);
}
}
/**
* Decompose the {@link GSRect} in four points starting from tl(), clockwise.
*
* @return an array of {@link GSPoint} in the order tl, tr, br, bl
*/
public GSPoint[] decomposeClockwise() {
GSPoint[] points = new GSPoint[] { tl(), new GSPoint(br().getX(), tl().getY()), br(), new GSPoint(tl().getX(), br().getY()) };
return points;
}
public GSRect normalize(double mintlx, double mintly, double width, double height) {
System.out.println("before normalizing " + this);
GSRect result = new GSRect((x - mintlx) / width, (y - mintly) / height, this.width / width, this.height / height);
System.out.println("after normalizing " + result);
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(height);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(width);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof GSRect))
return false;
GSRect it = (GSRect) obj;
return x == it.x && y == it.y && width == it.width && height == it.height;
}
@Override
public String toString() {
return String.format("{GSRect, tlx: %,.1f, tly: %,.1f, width: %,.1f, height: %,.1f}", x, y, width, height);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
|
package uk.ac.ebi.atlas.homepage;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import uk.ac.ebi.atlas.experiments.LatestExperimentsDao;
import uk.ac.ebi.atlas.experiments.LatestExperimentsService;
import uk.ac.ebi.atlas.model.experiment.ExperimentType;
import uk.ac.ebi.atlas.trader.ExperimentTrader;
import uk.ac.ebi.atlas.utils.ExperimentInfo;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:applicationContext.xml", "classpath:solrContext.xml", "classpath:dbContext.xml"})
public class LatestExperimentsServiceIT {
static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
@Inject
ExperimentTrader experimentTrader;
@Inject
LatestExperimentsDao latestExperimentsDao;
LatestExperimentsService subject;
@Before
public void setUp() throws Exception {
subject =
new LatestExperimentsService(
latestExperimentsDao, experimentTrader,
ImmutableSet.of(
ExperimentType.MICROARRAY_1COLOUR_MICRORNA_DIFFERENTIAL,
ExperimentType.MICROARRAY_1COLOUR_MRNA_DIFFERENTIAL,
ExperimentType.MICROARRAY_2COLOUR_MRNA_DIFFERENTIAL,
ExperimentType.RNASEQ_MRNA_DIFFERENTIAL,
ExperimentType.PROTEOMICS_BASELINE,
ExperimentType.RNASEQ_MRNA_BASELINE
));
}
public void assertThatExperimentsAreSortedByDate(List<ExperimentInfo> listOfExperimentInfo) throws Exception {
Iterator<ExperimentInfo> iterator = listOfExperimentInfo.iterator();
while (iterator.hasNext()) {
ExperimentInfo thisElement = iterator.next();
ExperimentInfo nextElement = iterator.hasNext() ? iterator.next() : null;
if (nextElement != null) {
Date thisDate = DATE_FORMAT.parse(thisElement.getLastUpdate());
Date nextDate = DATE_FORMAT.parse(nextElement.getLastUpdate());
if (!thisDate.equals(nextDate)) {
assertThat(
DATE_FORMAT.parse(thisElement.getLastUpdate())
.after(DATE_FORMAT.parse(nextElement.getLastUpdate())),
is(true));
}
}
}
}
@Test
public void fetchLatestExperimentsAttributes() throws Exception {
assertThat(subject.fetchLatestExperimentsAttributes().get("latestExperiments"), instanceOf(List.class));
assertThatExperimentsAreSortedByDate(
(List<ExperimentInfo>) subject.fetchLatestExperimentsAttributes().get("latestExperiments")
);
}
}
|
package com.woorea.openstack.heat;
import com.woorea.openstack.base.client.HttpMethod;
import com.woorea.openstack.base.client.OpenStackClient;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.heat.model.Resources;
public class ResourcesResource {
private final OpenStackClient client;
public ResourcesResource(OpenStackClient client) {
this.client = client;
}
public ListResources listResources(String name) {
return new ListResources(name);
}
public class ListResources extends OpenStackRequest<Resources> {
public ListResources(String name) {
super(client, HttpMethod.GET, "/stacks/" + name + "/resources", null, Resources.class);
}
}
}
|
package imagej;
import imagej.SampleInfo.ValueType;
import imagej.process.ImageUtils;
import imagej.process.Index;
import imagej.process.Span;
import imagej.process.TypeManager;
import imagej.process.operation.SetPlaneOperation;
import mpicbg.imglib.container.ContainerFactory;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.type.numeric.RealType;
import mpicbg.imglib.type.numeric.integer.ByteType;
import mpicbg.imglib.type.numeric.integer.IntType;
import mpicbg.imglib.type.numeric.integer.LongType;
import mpicbg.imglib.type.numeric.integer.ShortType;
import mpicbg.imglib.type.numeric.integer.UnsignedByteType;
import mpicbg.imglib.type.numeric.integer.UnsignedIntType;
import mpicbg.imglib.type.numeric.integer.UnsignedShortType;
import mpicbg.imglib.type.numeric.real.DoubleType;
import mpicbg.imglib.type.numeric.real.FloatType;
public class PlaneStack<T extends RealType<T>>
{
|
package net.runelite.http.service.xtea;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import net.runelite.cache.IndexType;
import net.runelite.cache.fs.Container;
import net.runelite.cache.util.Djb2;
import net.runelite.http.api.xtea.XteaKey;
import net.runelite.http.api.xtea.XteaRequest;
import net.runelite.http.service.cache.CacheService;
import net.runelite.http.service.cache.beans.ArchiveEntry;
import net.runelite.http.service.cache.beans.CacheEntry;
import net.runelite.http.service.util.exception.InternalServerErrorException;
import net.runelite.http.service.util.exception.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import org.springframework.web.bind.annotation.RestController;
import org.sql2o.Connection;
import org.sql2o.Query;
import org.sql2o.Sql2o;
@RestController
@RequestMapping("/xtea")
public class XteaService
{
private static final Logger logger = LoggerFactory.getLogger(XteaService.class);
private static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS `xtea` (\n"
+ " `id` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `region` int(11) NOT NULL,\n"
+ " `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n"
+ " `rev` int(11) NOT NULL,\n"
+ " `key1` int(11) NOT NULL,\n"
+ " `key2` int(11) NOT NULL,\n"
+ " `key3` int(11) NOT NULL,\n"
+ " `key4` int(11) NOT NULL,\n"
+ " PRIMARY KEY (`id`),\n"
+ " KEY `region` (`region`,`time`)\n"
+ ") ENGINE=InnoDB";
private final Sql2o sql2o;
private final CacheService cacheService;
@Autowired
public XteaService(
@Qualifier("Runelite SQL2O") Sql2o sql2o,
CacheService cacheService
)
{
this.sql2o = sql2o;
this.cacheService = cacheService;
try (Connection con = sql2o.beginTransaction())
{
con.createQuery(CREATE_SQL)
.executeUpdate();
}
}
private XteaEntry findLatestXtea(Connection con, int region)
{
return con.createQuery("select region, time, key1, key2, key3, key4 from xtea "
+ "where region = :region "
+ "order by time desc "
+ "limit 1")
.addParameter("region", region)
.executeAndFetchFirst(XteaEntry.class);
}
@RequestMapping(method = POST)
public void submit(@RequestBody XteaRequest xteaRequest)
{
try (Connection con = sql2o.beginTransaction())
{
CacheEntry cache = cacheService.findMostRecent();
if (cache == null)
{
throw new InternalServerErrorException("No most recent cache");
}
Query query = con.createQuery("insert into xtea (region, rev, key1, key2, key3, key4) "
+ "values (:region, :rev, :key1, :key2, :key3, :key4)");
for (XteaKey key : xteaRequest.getKeys())
{
int region = key.getRegion();
int[] keys = key.getKeys();
XteaEntry xteaEntry = findLatestXtea(con, region);
if (keys.length != 4)
{
throw new IllegalArgumentException("Key length must be 4");
}
// already have these?
if (xteaEntry != null
&& xteaEntry.getKey1() == keys[0]
&& xteaEntry.getKey2() == keys[1]
&& xteaEntry.getKey3() == keys[2]
&& xteaEntry.getKey4() == keys[3])
{
continue;
}
if (!checkKeys(cache, region, keys))
{
continue;
}
query.addParameter("region", region)
.addParameter("rev", xteaRequest.getRevision())
.addParameter("key1", keys[0])
.addParameter("key2", keys[1])
.addParameter("key3", keys[2])
.addParameter("key4", keys[3])
.addToBatch();
}
query.executeBatch();
con.commit();
}
}
@RequestMapping
public List<XteaKey> get()
{
try (Connection con = sql2o.open())
{
List<XteaEntry> entries = con.createQuery(
"select t1.region, t1.time, t2.rev, t2.key1, t2.key2, t2.key3, t2.key4 from " +
"(select region,max(time) as time from xtea group by region) t1 " +
"join xtea t2 on t1.region = t2.region and t1.time = t2.time")
.executeAndFetch(XteaEntry.class);
return entries.stream()
.map(XteaService::entryToKey)
.collect(Collectors.toList());
}
}
@RequestMapping("/{region}")
public XteaKey getRegion(@PathVariable int region)
{
XteaEntry entry;
try (Connection con = sql2o.open())
{
entry = con.createQuery("select region, time, rev, key1, key2, key3, key4 from xtea "
+ "where region = :region order by time desc limit 1")
.addParameter("region", region)
.executeAndFetchFirst(XteaEntry.class);
}
if (entry == null)
{
throw new NotFoundException();
}
return entryToKey(entry);
}
private boolean checkKeys(CacheEntry cache, int regionId, int[] keys)
{
int x = regionId >>> 8;
int y = regionId & 0xFF;
String archiveName = new StringBuilder()
.append('l')
.append(x)
.append('_')
.append(y)
.toString();
int archiveNameHash = Djb2.hash(archiveName);
ArchiveEntry archiveEntry = cacheService.findArchiveForTypeAndName(cache, IndexType.MAPS, archiveNameHash);
if (archiveEntry == null)
{
throw new InternalServerErrorException("Unable to find archive for region");
}
byte[] data = cacheService.getArchive(archiveEntry);
if (data == null)
{
throw new InternalServerErrorException("Unable to get archive data");
}
try
{
Container.decompress(data, keys);
return true;
}
catch (IOException ex)
{
return false;
}
}
private static XteaKey entryToKey(XteaEntry xe)
{
XteaKey xteaKey = new XteaKey();
xteaKey.setRegion(xe.getRegion());
xteaKey.setKeys(new int[]
{
xe.getKey1(),
xe.getKey2(),
xe.getKey3(),
xe.getKey4()
});
return xteaKey;
}
}
|
package org.mousephenotype.cda.indexers;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.mousephenotype.cda.indexers.exceptions.IndexerException;
import org.mousephenotype.cda.solr.service.dto.Allele2DTO;
import org.mousephenotype.cda.utilities.RunStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@EnableAutoConfiguration
public class Allele2Indexer extends AbstractIndexer implements CommandLineRunner {
@NotNull
@Value("${allele2File}")
private String pathToAlleleFile;
@Autowired
@Qualifier("allele2Indexing")
private SolrClient allele2Core;
Integer alleleDocCount;
Map<String, Integer> columns = new HashMap<>();
@Override
public RunStatus run() throws IndexerException, IOException, SolrServerException, SQLException {
RunStatus runStatus = new RunStatus();
allele2Core.deleteByQuery("*:*");
allele2Core.commit();
long time = System.currentTimeMillis();
BufferedReader in = new BufferedReader(new FileReader(new File(pathToAlleleFile)));
String[] header = in.readLine().split("\t");
for (int i = 0; i < header.length; i++){
columns.put(header[i], i);
}
int index = 0 ;
String line = in.readLine();
while (line != null){
String[] array = line.split("\t", -1);
index ++;
Allele2DTO doc = new Allele2DTO();
doc.setAlleleCategory(getValueFor(Allele2DTO.ALLELE_CATEGORY, array, columns, runStatus));
doc.setAlleleDescription(getValueFor(Allele2DTO.ALLELE_DESCRIPTION,array, columns, runStatus));
doc.setAlleleImage(getValueFor(Allele2DTO.ALLELE_IMAGE,array, columns, runStatus));
doc.setAlleleMgiAccessionId(getValueFor(Allele2DTO.ALLELE_MGI_ACCESSION_ID,array, columns, runStatus));
doc.setAlleleName(getValueFor(Allele2DTO.ALLELE_NAME,array, columns, runStatus));
doc.setAlleleSimpleImage(getValueFor(Allele2DTO.ALLELE_SIMPLE_IMAGE,array, columns, runStatus));
doc.setAlleleType(getValueFor(Allele2DTO.ALLELE_TYPE,array, columns, runStatus));
doc.setAlleleFeatures(getListValueFor(Allele2DTO.ALLELE_FEATURES, array, columns, runStatus));
doc.setCassette(getValueFor(Allele2DTO.CASSETTE,array, columns, runStatus));
doc.setDesignId(getValueFor(Allele2DTO.DESIGN_ID,array, columns, runStatus));
doc.setEsCellStatus(getValueFor(Allele2DTO.ES_CELL_STATUS,array, columns, runStatus));
doc.setEsCellAvailable(getBooleanValueFor(Allele2DTO.ES_CELL_AVAILABLE,array, columns, runStatus));
doc.setFeatureChromosome(getValueFor(Allele2DTO.FEATURE_CHROMOSOME,array, columns, runStatus));
doc.setFeatureStrand(getValueFor(Allele2DTO.FEATURE_STRAND,array, columns, runStatus));
doc.setFeatureCoordEnd(getLongValueFor(Allele2DTO.FEATURE_COORD_END,array, columns, runStatus));
doc.setFeatureCoordStart(getLongValueFor(Allele2DTO.FEAURE_COORD_START,array, columns, runStatus));
doc.setFeatureType(getValueFor(Allele2DTO.FEATURE_TYPE,array, columns, runStatus));
doc.setGenbankFile(getValueFor(Allele2DTO.GENBANK_FILE,array, columns, runStatus));
doc.setGeneModelIds(getListValueFor(Allele2DTO.GENE_MODEL_IDS,array, columns, runStatus));
doc.setGeneticMapLinks(getListValueFor(Allele2DTO.GENETIC_MAP_LINKS,array, columns, runStatus));
doc.setIkmcProject(getListValueFor(Allele2DTO.IKMC_PROJECT,array, columns, runStatus));
doc.setLatestEsCellStatus(getValueFor(Allele2DTO.LATEST_ES_CELL_STATUS,array, columns, runStatus));
doc.setLatestMouseStatus(getValueFor(Allele2DTO.LATEST_MOUSE_STATUS,array, columns, runStatus));
doc.setLatestPhenotypeComplete(getValueFor(Allele2DTO.LATEST_PHENOTYPE_COMPLETE,array, columns, runStatus));
doc.setLatestPhenotypeStarted(getValueFor(Allele2DTO.LATEST_PHENOTYPE_STARTED,array, columns, runStatus));
doc.setLatestProjectStatus(getValueFor(Allele2DTO.LATEST_PROJECT_STATUS,array, columns, runStatus));
doc.setLatestProjectStatusLegacy(getValueFor(Allele2DTO.LATEST_PROJECT_STATUS_LEGACY,array, columns, runStatus));
doc.setLinks(getListValueFor(Allele2DTO.LINKS,array, columns, runStatus));
doc.setMarkerType(getValueFor(Allele2DTO.MARKER_TYPE,array, columns, runStatus));
doc.setMarkerSymbol(getValueFor(Allele2DTO.MARKER_SYMBOL, array, columns, runStatus));
doc.setMgiAccessionId(getValueFor(Allele2DTO.MGI_ACCESSION_ID, array, columns, runStatus));
doc.setMarkerName(getValueFor(Allele2DTO.MARKER_NAME,array, columns, runStatus));
doc.setMouseAvailable(getBooleanValueFor(Allele2DTO.MOUSE_AVAILABLE, array, columns, runStatus));
doc.setMutationType(getValueFor(Allele2DTO.MUTATION_TYPE,array,columns, runStatus));
doc.setMouseStatus(getValueFor(Allele2DTO.MOUSE_STATUS, array,columns, runStatus));
doc.setPhenotypeStatus(getValueFor(Allele2DTO.PHENOTYPE_STATUS,array, columns, runStatus));
doc.setPhenotypingCentre(getValueFor(Allele2DTO.PHENOTYPING_CENTRE,array, columns, runStatus));
doc.setPhenotypingCentres(getListValueFor(Allele2DTO.PHENOTYPING_CENTRES,array, columns, runStatus));
doc.setProductionCentre(getValueFor(Allele2DTO.PRODUCTION_CENTRE,array, columns, runStatus));
doc.setProductionCentres(getListValueFor(Allele2DTO.PRODUCTION_CENTRES,array, columns, runStatus));
doc.setPipeline(getListValueFor(Allele2DTO.PIPELINE,array, columns, runStatus));
doc.setSequenceMapLinks(getListValueFor(Allele2DTO.SEQUENCE_MAP_LINKS, array, columns, runStatus));
doc.setSynonym(getListValueFor(Allele2DTO.SYNONYM, array, columns, runStatus));
doc.setTargetingVectorAvailable(getBooleanValueFor(Allele2DTO.TARGETING_VECTOR_AVAILABLE, array, columns, runStatus));
doc.setType(getValueFor(Allele2DTO.TYPE, array, columns, runStatus));
doc.setVectorAlleleImage(getValueFor(Allele2DTO.VECTOR_ALLELE_IMAGE, array, columns, runStatus));
doc.setVectorGenbankLink(getValueFor(Allele2DTO.VECTOR_GENBANK_LINK, array, columns, runStatus));
doc.setWithoutAlleleFeatures(getListValueFor(Allele2DTO.WITHOUT_ALLELE_FEATURES, array, columns, runStatus));
line = in.readLine();
allele2Core.addBean(doc);
if (index % 1000 == 0) {
allele2Core.commit();
// System.out.println("committed " + index);
}
}
allele2Core.commit();
alleleDocCount = index;
System.out.println("Indexing took " + (System.currentTimeMillis() - time));
return runStatus;
}
@Override
public RunStatus validateBuild() throws IndexerException {
RunStatus runStatus = new RunStatus();
Long actualSolrDocumentCount = getDocumentCount(allele2Core);
if (actualSolrDocumentCount <= alleleDocCount) {
runStatus.addError("Expected " + alleleDocCount + " documents. Actual count: " + actualSolrDocumentCount + ".");
}
return runStatus;
}
public static void main(String[] args) throws IndexerException {
SpringApplication.run(Allele2Indexer.class, args);
}
}
|
package com.thinkbiganalytics.feedmgr.service.template;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.thinkbiganalytics.feedmgr.rest.model.RegisteredTemplate;
import com.thinkbiganalytics.json.ObjectMapperSerializer;
import com.thinkbiganalytics.metadata.api.feedmgr.feed.FeedManagerFeed;
import com.thinkbiganalytics.metadata.api.feedmgr.template.FeedManagerTemplate;
import com.thinkbiganalytics.metadata.api.feedmgr.template.FeedManagerTemplateProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
public class TemplateModelTransform {
@Inject
FeedManagerTemplateProvider templateProvider;
public final Function<FeedManagerTemplate, RegisteredTemplate>
DOMAIN_TO_REGISTERED_TEMPLATE =
new Function<FeedManagerTemplate, RegisteredTemplate>() {
@Override
public RegisteredTemplate apply(FeedManagerTemplate domain) {
String json = domain.getJson();
RegisteredTemplate template = ObjectMapperSerializer.deserialize(json, RegisteredTemplate.class);
template.setId(domain.getId().toString());
template.setState(domain.getState().name());
List<FeedManagerFeed> feeds = domain.getFeeds();
template.setFeedsCount(feeds == null ? 0 : feeds.size());
if(domain.getCreatedTime() != null) {
template.setCreateDate(domain.getCreatedTime().toDate());
}
if(domain.getModifiedTime() != null) {
template.setUpdateDate(domain.getModifiedTime().toDate());
}
return template;
}
};
public final Function<RegisteredTemplate, FeedManagerTemplate>
REGISTERED_TEMPLATE_TO_DOMAIN =
new Function<RegisteredTemplate,FeedManagerTemplate>() {
@Override
public FeedManagerTemplate apply(RegisteredTemplate registeredTemplate) {
//resolve the id
FeedManagerTemplate.ID domainId = registeredTemplate.getId() != null ? templateProvider.resolveId(registeredTemplate.getId()) : null;
FeedManagerTemplate domain = null;
if (domainId != null) {
domain = templateProvider.findById(domainId);
}
if (domain == null) {
domain = templateProvider.ensureTemplate(registeredTemplate.getTemplateName());
}
domainId = domain.getId();
String json = ObjectMapperSerializer.serialize(registeredTemplate);
domain.setNifiTemplateId(registeredTemplate.getNifiTemplateId());
domain.setAllowPreconditions(registeredTemplate.isAllowPreconditions());
domain.setName(registeredTemplate.getTemplateName());
domain.setDataTransformation(registeredTemplate.isDataTransformation());
domain.setDefineTable(registeredTemplate.isDefineTable());
domain.setIcon(registeredTemplate.getIcon());
domain.setIconColor(registeredTemplate.getIconColor());
domain.setDescription(registeredTemplate.getDescription());
domain.setJson(json);
FeedManagerTemplate.State state = FeedManagerTemplate.State.ENABLED;
try {
state = FeedManagerTemplate.State.valueOf(registeredTemplate.getState());
} catch (IllegalArgumentException e) {
// make enabled by default
}
domain.setState(state);
//assign the id back to the ui model
registeredTemplate.setId(domainId.toString());
return domain;
}
};
public List<RegisteredTemplate> domainToRegisteredTemplate(Collection<FeedManagerTemplate> domain) {
return new ArrayList<>(Collections2.transform(domain, DOMAIN_TO_REGISTERED_TEMPLATE));
}
public RegisteredTemplate domainToRegisteredTemplate(FeedManagerTemplate domain) {
return DOMAIN_TO_REGISTERED_TEMPLATE.apply(domain);
}
public List<FeedManagerTemplate> registeredTemplateToDomain(Collection<RegisteredTemplate> registeredTemplates) {
return new ArrayList<>(Collections2.transform(registeredTemplates, REGISTERED_TEMPLATE_TO_DOMAIN));
}
}
|
package com.wavefront.metrics;
import com.google.common.collect.ImmutableList;
import com.wavefront.common.Pair;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.WavefrontHistogram;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import static com.google.common.truth.Truth.assertThat;
/**
* Basic unit tests around {@link JsonMetricsGenerator}
*
* @author Tim Schmidt (tim@wavefront.com).
*/
public class JsonMetricsGeneratorTest {
private AtomicLong time = new AtomicLong(0);
private MetricsRegistry testRegistry;
private final ObjectMapper objectMapper = new ObjectMapper();
@Before
public void setup() {
testRegistry = new MetricsRegistry();
}
private String generate(boolean includeVMMetrics,
boolean includeBuildMetrics,
boolean clearMetrics,
MetricTranslator metricTranslator) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonMetricsGenerator.generateJsonMetrics(baos, testRegistry, includeVMMetrics, includeBuildMetrics, clearMetrics,
metricTranslator);
return new String(baos.toByteArray());
}
/**
* @param map A raw map.
* @param key A key.
* @param clazz See T.
* @param <T> The expected dynamic type of map.get(key)
* @return map.get(key) if it exists and is the right type. Otherwise, fail the calling test.
*/
private <T> T safeGet(Map map, String key, Class<T> clazz) {
assertThat(map.containsKey(key)).isTrue();
assertThat(map.get(key)).isInstanceOf(clazz);
return clazz.cast(map.get(key));
}
@Test
public void testJvmMetrics() throws IOException {
String json = generate(true, false, false, null);
Map top = objectMapper.readValue(json, Map.class);
Map jvm = safeGet(top, "jvm", Map.class);
Map memory = safeGet(jvm, "memory", Map.class);
safeGet(memory, "totalInit", Double.class);
safeGet(memory, "memory_pool_usages", Map.class);
Map buffers = safeGet(jvm, "buffers", Map.class);
safeGet(buffers, "direct", Map.class);
safeGet(buffers, "mapped", Map.class);
safeGet(jvm, "fd_usage", Double.class);
safeGet(jvm, "current_time", Long.class);
Map threadStates = safeGet(jvm, "thread-states", Map.class);
safeGet(threadStates, "runnable", Double.class);
Map garbageCollectors = safeGet(jvm, "garbage-collectors", Map.class);
assertThat(threadStates).isNotEmpty();
// Check that any GC has a "runs" entry.
String key = (String) garbageCollectors.keySet().iterator().next(); // e.g. "PS MarkSweep"
Map gcMap = safeGet(garbageCollectors, key, Map.class);
safeGet(gcMap, "runs", Double.class);
safeGet(gcMap, "time", Double.class);
}
@Test
public void testTranslator() throws IOException {
Counter counter = testRegistry.newCounter(new MetricName("test", "foo", "bar"));
counter.inc();
counter.inc();
String json = generate(false, false, false, metricNameMetricPair -> {
assertThat(metricNameMetricPair._1).isEquivalentAccordingToCompareTo(new MetricName("test", "foo", "bar"));
assertThat(metricNameMetricPair._2).isInstanceOf(Counter.class);
assertThat(((Counter)metricNameMetricPair._2).count()).isEqualTo(2);
return new Pair<>(new MetricName("test", "baz", "qux"), metricNameMetricPair._2);
});
assertThat(json).isEqualTo("{\"test.qux\":2}");
json = generate(false, false, false, metricNameMetricPair -> null);
assertThat(json).isEqualTo("{}");
}
@Test
public void testYammerHistogram() throws IOException {
Histogram wh = testRegistry.newHistogram(new MetricName("test", "", "metric"), false);
wh.update(10);
wh.update(100);
wh.update(1000);
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"count\":3,\"min\":10.0,\"max\":1000.0,\"mean\":370.0,\"sum\":1110.0,\"stddev\":547.4486277268397,\"median\":100.0,\"p75\":1000.0,\"p95\":1000.0,\"p99\":1000.0,\"p999\":1000.0}}");
}
@Test
public void testWavefrontHistogram() throws IOException {
Histogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.update(10);
wh.update(100);
wh.update(1000);
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":3,\"startMillis\":0,\"durationMillis\":60000,\"means\":[10.0,100.0,1000.0],\"counts\":[1,1,1]}]}}");
}
@Test
public void testWavefrontHistogramClear() throws IOException {
Histogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.update(10);
generate(false, false, true, null);
wh.update(100);
String json = generate(false, false, true, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":1,\"startMillis\":0,\"durationMillis\":60000,\"means\":[100.0],\"counts\":[1]}]}}");
}
@Test
public void testWavefrontHistogramNoClear() throws IOException {
Histogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.update(10);
generate(false, false, false, null);
wh.update(100);
String json = generate(false, false, true, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":2,\"startMillis\":0,\"durationMillis\":60000,\"means\":[10.0,100.0],\"counts\":[1,1]}]}}");
}
@Test
public void testWavefrontHistogramSpanMultipleMinutes() throws IOException {
Histogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.update(10);
wh.update(100);
time.set(61 * 1000);
wh.update(1000);
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":2,\"startMillis\":0,\"durationMillis\":60000,\"means\":[10.0,100.0],\"counts\":[1,1]},{\"count\":1,\"startMillis\":60000,\"durationMillis\":60000,\"means\":[1000.0],\"counts\":[1]}]}}");
}
@Test
public void testWavefrontHistogramPrunesOldBins() throws IOException {
Histogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.update(10);
time.set(61 * 1000);
wh.update(100);
time.set(121 * 1000);
wh.update(1000);
time.set(181 * 1000);
wh.update(10000);
time.set(241 * 1000);
wh.update(100000);
time.set(301 * 1000);
wh.update(100001);
time.set(361 * 1000);
wh.update(100011);
time.set(421 * 1000);
wh.update(100111);
time.set(481 * 1000);
wh.update(101111);
time.set(541 * 1000);
wh.update(111111);
time.set(601 * 1000);
wh.update(111112);
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":1,\"startMillis\":60000,\"durationMillis\":60000,\"means\":[100.0],\"counts\":[1]},{\"count\":1,\"startMillis\":120000,\"durationMillis\":60000,\"means\":[1000.0],\"counts\":[1]},{\"count\":1,\"startMillis\":180000,\"durationMillis\":60000,\"means\":[10000.0],\"counts\":[1]},{\"count\":1,\"startMillis\":240000,\"durationMillis\":60000,\"means\":[100000.0],\"counts\":[1]},{\"count\":1,\"startMillis\":300000,\"durationMillis\":60000,\"means\":[100001.0],\"counts\":[1]},{\"count\":1,\"startMillis\":360000,\"durationMillis\":60000,\"means\":[100011.0],\"counts\":[1]},{\"count\":1,\"startMillis\":420000,\"durationMillis\":60000,\"means\":[100111.0],\"counts\":[1]},{\"count\":1,\"startMillis\":480000,\"durationMillis\":60000,\"means\":[101111.0],\"counts\":[1]},{\"count\":1,\"startMillis\":540000,\"durationMillis\":60000,\"means\":[111111.0],\"counts\":[1]},{\"count\":1,\"startMillis\":600000,\"durationMillis\":60000,\"means\":[111112.0],\"counts\":[1]}]}}");
}
@Test
public void testWavefrontHistogramBulkUpdate() throws IOException {
WavefrontHistogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.bulkUpdate(ImmutableList.of(15d, 30d, 45d), ImmutableList.of(1, 5, 1));
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":7,\"startMillis\":0,\"durationMillis\":60000,\"means\":[15.0,30.0,45.0],\"counts\":[1,5,1]}]}}");
}
@Test
public void testWavefrontHistogramBulkUpdateHandlesMismatchedLengths() throws IOException {
WavefrontHistogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.bulkUpdate(ImmutableList.of(15d, 30d, 45d, 100d), ImmutableList.of(1, 5, 1));
wh.bulkUpdate(ImmutableList.of(1d, 2d, 3d), ImmutableList.of(1, 1, 1, 9));
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[{\"count\":10,\"startMillis\":0,\"durationMillis\":60000,\"means\":[1.0,2.0,3.0,15.0,30.0,45.0],\"counts\":[1,1,1,1,5,1]}]}}");
}
@Test
public void testWavefrontHistogramBulkUpdateHandlesNullParams() throws IOException {
WavefrontHistogram wh = WavefrontHistogram.get(testRegistry, new MetricName("test", "", "metric"), time::get);
wh.bulkUpdate(null, ImmutableList.of(1, 5, 1));
wh.bulkUpdate(ImmutableList.of(15d, 30d, 45d, 100d), null);
wh.bulkUpdate(null, null);
String json = generate(false, false, false, null);
assertThat(json).isEqualTo("{\"test.metric\":{\"bins\":[]}}");
}
}
|
// Hello from Bryan!
package ie.dit;
import ddf.minim.AudioInput;
import ddf.minim.AudioSample;
import ddf.minim.Minim;
import ddf.minim.analysis.FFT;
import ddf.minim.analysis.WindowFunction;
import processing.core.PApplet;
public class AudioViz2017 extends PApplet{
Minim minim;
AudioSample audioInput;
FFT fft;
PitchSpeller pitchSpeller = new PitchSpeller();
static final int FRAME_SIZE = 2048;
static final int SAMPLE_RATE = 44100;
public void setup()
{
minim = new Minim(this);
//audioInput = minim.getLineIn(Minim.MONO, FRAME_SIZE, SAMPLE_RATE, 16);
audioInput = minim.loadSample("scale.wav", FRAME_SIZE);
fft = new FFT(FRAME_SIZE, SAMPLE_RATE);
tf.loadTunes();
}
boolean lastPressed = false;
String transcription = "";
TuneFinder tf = new TuneFinder();
public void draw()
{
if (keyPressed && key == ' ' && ! lastPressed)
{
audioInput.trigger();
lastPressed = true;
}
else
{
lastPressed = false;
}
background(0);
stroke(255);
float mid = height / 2.0f;
float average = 0;
int count = 0;
for(int i = 1 ; i < audioInput.bufferSize() ; i ++)
{
line(i, mid , i, mid + audioInput.left.get(i) * mid);
average += Math.abs(audioInput.left.get(i));
if (audioInput.left.get(i -1) > 0 && audioInput.left.get(i) <= 0)
{
count ++;
}
}
average /= audioInput.bufferSize();
float frequency = count * (SAMPLE_RATE / FRAME_SIZE);
fill(255);
fft.window(FFT.HAMMING);
fft.forward(audioInput.left);
stroke(0, 255, 255);
int maxIndex = -1;
float maxEnergy = Float.MIN_VALUE;
for(int i = 0 ; i < fft.specSize(); i ++)
{
float energy = fft.getBand(i);
if (energy > maxEnergy)
{
maxEnergy = energy;
maxIndex = i;
}
line(i, height, i, height - (energy * 50));
}
float fftFreq = fft.indexToFreq(maxIndex);
if (average > 0.05f)
{
text("Zero crossings Frequency: " + frequency, 10,10);
text("FFT Frequency: " + fftFreq, 10,30);
String zcSpell = pitchSpeller.spell(frequency);
String fftSpell = pitchSpeller.spell(fftFreq);
text("ZC Spelling: " + zcSpell, 10, 50);
text("FFT Spelling: " + fftSpell, 10, 70);
if (transcription.length() > 0)
{
String lastChar = transcription.substring(transcription.length() - 1);
if (!lastChar.equals(fftSpell))
{
transcription += fftSpell;
}
}
else
{
transcription += fftSpell;
}
}
text("Transcription: " + transcription, 10, 70);
noStroke();
fill(0, 255, 0);
float min = 100;
float target = min + average * mid * 2;
circleRadius = lerp(circleRadius, target, 0.1f);
//ellipse(mid, mid, circleRadius, circleRadius);
}
float circleRadius = 0;
public void settings()
{
size(1024, 512);
}
public static void main(String[] args) {
String[] a = {"MAIN"};
PApplet.runSketch( a, new AudioViz2017());
}
}
|
package ui;
import game.Room;
import game.Square.Type;
import game.Square;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Class Which constitutes the board logic within the Game
* @author Jarred Hone, Greg Oswald
*
*/
public class Board {
String filename;
private Square[][] board = new Square[26][26]; //2D Array representing the board < -- Uninitialised
public Board(){
//fillInitialArray();// will cause nullPointerException() if uncommented
}
/**
* Fills array with initial values from a text file using a parser - should only need to be called once and the base board will never change.
*/
public void setFileName(String filename){
this.filename = filename;
}
private void fillInitialArray(){
int x = 0;
int y = 0;
File text;
try{
//Read File and set up Scanner
text = new File(filename);
System.out.println(filename);
Scanner scan = new Scanner(text);
String letter = "x";
while(scan.hasNextLine()){ //While there is a next line of input
String line = scan.nextLine(); //Store the entire next line as a string
Scanner lineSplit = new Scanner(line); //New scanner on the string line to break it into parts.
for(x=0; x<line.length();x++){ //Loops along the line in sync with array
if(lineSplit.hasNext()){
letter = lineSplit.next(); //The letter we will be dealing with in the current iteration.
}
/**
* Parsing Begins
*/
//TODO Still needs to parse a letter for stairs which are a type of portal. They are not in the text file yet though
if(letter.equals('s')){ //study
board[x][y] = new Square(Type.STUDY);
}
else if(letter.equals('w')){ //wall
board[x][y] = new Square(Type.WALL);
}
else if(letter.equals('h')){ //hall
board[x][y] = new Square(Type.HALL);
}
else if(letter.equals('d')){ //door
board[x][y] = new Square(Type.DOOR);
}
else if(letter.equals('l')){ //Lounge
board[x][y] = new Square(Type.LOUNGE);
}
else if(letter.equals('i')){ //Library
board[x][y] = new Square(Type.LIBRARY);
}
else if(letter.equals('0')){ //Cellar
board[x][y] = new Square(Type.CELLAR);
}
else if(letter.equals('p')){ //dining room
board[x][y] = new Square(Type.DININGROOM);
}
else if(letter.equals('t')){ //Billiard Room
board[x][y] = new Square(Type.BILLIARDROOM);
}
else if(letter.equals('b')){ //Ballroom
board[x][y] = new Square(Type.BALLROOM);
}
else if(letter.equals('k')){ //Kitchen
board[x][y] = new Square(Type.KITCHEN);
}
else if(letter.equals('c')){ //Conservatory
board[x][y] = new Square(Type.CONSERVATORY);
}
/**
* Special Case - The Spawn points for the players.
*/
else if(letter.equals('1')){ //Professor Plum
board[x][y] = new Square(Type.PLUM);
}
else if(letter.equals('2')){ //Miss Scarlett
board[x][y] = new Square(Type.SCARLETT);
}
else if(letter.equals('3')){ //Col. Mustard
board[x][y] = new Square(Type.MUSTARD);
}
else if(letter.equals('4')){ //Mrs Peacock
board[x][y] = new Square(Type.PEACOCK);
}
else if(letter.equals('5')){ //Mr. Green
board[x][y] = new Square(Type.GREEN);
}
else if(letter.equals('6')){ //Mrs White
board[x][y] = new Square(Type.WHITE);
}
else{ //Letter was unrecognised.
}
}
y++; //increments y by 1, so that the 2D array drops down one.
x=0; //Reset x back to 0 to start from the left again.
}
//function for testing - prints out the array
for(int r=0; r<board.length; r++) {
for(int c=0; c<board[r].length; c++)
if(board[r][c]!= null){
System.out.print(board[r][c] + " ");
}
System.out.println();
}
}
catch(FileNotFoundException e){
System.out.println("File was not found");
}
}
}
|
package com.memoir44.vassal;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.xml.transform.ErrorListener;
import VASSAL.Info;
import VASSAL.build.BadDataReport;
import VASSAL.build.GameModule;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.GameState;
import VASSAL.command.Command;
import VASSAL.i18n.Resources;
import VASSAL.tools.BugUtils;
import VASSAL.tools.DataArchive;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.imageop.Op;
import VASSAL.tools.imageop.SourceOp;
public class M44ScenarioChooser extends JDialog {
private JDialog thisFrame;
private JPanel mainPanel;
//private JPanel listPanel;
private JPanel filterPanel;
private JPanel buttonPanel;
private JTable scenarioList;
private ScenarioTableModel scenarioModel;
private JPanel jpText;
private JTextField jtText;
private String filterText = "";
private JPanel jpFront;
private JCheckBox[] jcFront;
private String[] frontNames = {"Western", "Eastern", "Pacific", "Mediterranean"};
private boolean[] filterFronts = new boolean[frontNames.length + 1];
private JPanel jpExpansions;
//private JCheckBox[] jcExpansions;
private JComboBox jcExpansions;
private int indexAirPackExpansion = -1;
private String[] expansionNames = {"Base Game", "Terrain Pack", "Eastern", "Pacific", "Air Pack", "Mediterranean", "Hedgerow Hell", "Tigers in the Snow", "Sword of Stalingrad", "Disaster at Dieppe", "Breakthrough", "Winter Wars", "Campaign Book Vol. 1", "Campaign Book Vol. 2", "Vercors Campaign", "Audie Murphy", "Invasion of Crete", "D-Day Landings", "Through Jungle and Desert"};
private String[] expansionCodes = {"ST", "TP", "EF", "PT", "AA", "MT", "HH", "TS", "SS", "DD", "BT", "WW", "CB", "C2", "VC", "DM", "IC", "DY", "JD"};
private String[] expansionMenu = {"All", "Base Game", "Terrain Pack", "Eastern", "Pacific", "Air Pack", "Mediterranean", "Hedgerow Hell", "Tigers in the Snow", "Sword of Stalingrad", "Disaster at Dieppe", "Breakthrough", "Winter Wars", "Campaign Book Vol. 1", "Campaign Book Vol. 2", "Vercors Campaign", "Audie Murphy", "Invasion of Crete", "D-Day Landings", "Through Jungle and Desert"};
private boolean[] filterExpansions = new boolean[expansionNames.length + 2];
private JPanel jpType;
private JCheckBox[] jcType;
private String breaklordLabel = "OverThrough";
private String[] typeNames = {"Inland", "Beach", "Winter", "Desert", "BT-Inland", "BT-Beach", "BT-Winter", "BT-Desert", "OL-Inland", "OL-Beach", "OL-Winter", "OL-Desert", "BT-Extended", breaklordLabel, "MultiMap", "HexMap"};
private boolean[] filterTypes = new boolean[typeNames.length + 1];
private JPanel jpYear;
private JCheckBox[] jcYear;
private String[] yearNames = {"1936", "1937", "1938", "1939", "1940", "1941", "1942", "1943", "1944", "1945"};
private String[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private boolean[] filterYears = new boolean[yearNames.length + 1];
private JCheckBox jcOfficialScenarios;
private boolean filterOfficial = false;
private JCheckBox jcSFTF;
private boolean filterSFTF = false;
private JPanel numScenPanel;
private JLabel jlNumScen;
private JButton viewOnlineButton;
private JButton randomButton;
private JButton cancelButton;
private JButton selectButton;
private JPanel previewPanel;
private JComponent previewPane;
private Image previewImage = null;
private JSplitPane splitPane;
private static boolean checkedSetups = false;
private GameState myGameState;
private Vector<M44Setup> setups = new Vector<M44Setup>();
private Vector<M44Series> series = new Vector<M44Series>();
public M44ScenarioChooser(GameState gameState) {
myGameState = gameState;
jbInit();
}
private static void WriteLine(String msgLine) {
FormattedString cStr = new FormattedString("- " + msgLine);
final Command cc = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), cStr.getLocalizedText());
cc.execute();
GameModule.getGameModule().sendAndLog(cc);
}
private void jbInit() {
thisFrame = this;
Dimension dim = getToolkit().getScreenSize();
int width, height;
width = dim.width - 50;
height = dim.height - 30;
if (width > 1900)
width = 1900;
this.setTitle("Choose a Memoir '44 Scenario");
this.setSize(width, height);
this.setLocation((dim.width - width) / 2, (dim.height - height) / 2);
this.setResizable(true);
mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//listPanel = new JPanel(new BorderLayout());
filterPanel = new JPanel();
filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));
buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
Collection<GameComponent> comps = myGameState.getGameComponents();
Iterator<GameComponent> it = comps.iterator();
do {
GameComponent comp = it.next();
if (comp instanceof M44Setup) {
M44Setup setup = (M44Setup) comp;
// add to our list
setups.add(setup);
}
if (comp instanceof M44Series) {
series.add((M44Series) comp);
}
} while (it.hasNext());
// process classifieds
for (int i = 0; i < setups.size(); i++)
{
M44Setup setup1 = setups.get(i);
if (setup1.classified)
{
for (int j = 0; j < setups.size(); j++)
{
M44Setup setup2 = setups.get(j);
if (!setup1.equals(setup2) && setup1.fileName.equals(setup2.fileName))
{
setups.remove(i);
i
break;
}
}
}
}
// check for missing files
if (!checkedSetups) {
Runnable checkRunnable = new Runnable() {
public void run() {
GameModule gameModule = GameModule.getGameModule();
DataArchive dataArchive = gameModule.getDataArchive();
for (int i = 0; i < setups.size(); i++) {
M44Setup setup = setups.get(i);
if (!setup.classified)
{
// test to see if this setup is valid
try {
if (dataArchive.getURL(setup.getFileName()) == null) {
//WriteLine("Error in module, could not find pre-defined setup file " + setup.getFileName());
ErrorDialog.dataError(new BadDataReport(Resources.getString("Error.not_found", "Setup"), setup.getFileName()));
}
} catch (Exception e1) {
//WriteLine("Error in module, could not find pre-defined setup file " + setup.getFileName());
ErrorDialog.dataError(new BadDataReport(Resources.getString("Error.not_found", "Setup"), setup.getFileName(), e1));
}
String imageName = setup.fileName + ".jpg";
try {
SourceOp result = Op.load(imageName);
if (result == null || result.getHeight() != 500) {
//WriteLine("Error in module, could not find proper pre-defined image preview file " + imageName);
//WriteLine(Integer.toString(result.getHeight()));
ErrorDialog.dataError(new BadDataReport(Resources.getString("Error.not_found", "Image with correct size"), imageName));
}
} catch (Exception e1) {
//WriteLine("Error in module, could not find proper pre-defined image preview file " + imageName);
ErrorDialog.dataError(new BadDataReport(Resources.getString("Error.not_found", "Image"), imageName, e1));
}
}
}
}
};
checkedSetups = true;
Thread checkThread = new Thread(checkRunnable);
checkThread.start();
}
if (series.size() == 0)
{
int num = expansionNames.length;
for (int i = 0; i < num; i++)
series.add(new M44Series(expansionNames[i], expansionCodes[i]));
}
filterExpansions = new boolean[series.size()];
Comparator<M44Setup> sortScenarios = new ScenarioSorter();
Collections.sort(setups, sortScenarios);
Comparator<M44Series> sortSeries = new SeriesSorter();
Collections.sort(series, sortSeries);
for (int i = series.size() - 1; i > 0; i
{
if (series.get(i-1).getConfigureName().equals(series.get(i).getConfigureName()))
series.remove(i);
}
for (int i = 0; i < series.size(); i++)
if (series.get(i).prefix.equals("AA"))
indexAirPackExpansion = i;
expansionMenu = new String[series.size()+1];
expansionMenu[0] = "All";
int num = series.size();
for (int i = 0; i < num; i++)
expansionMenu[i+1] = series.get(i).getAttributeValueString(M44Series.NAME);
numScenPanel = new JPanel();
numScenPanel.setBorder(BorderFactory.createTitledBorder("Scenarios"));
numScenPanel.setMaximumSize(new Dimension(32000, 24));
jlNumScen = new JLabel("Number-of-Scenarios");
numScenPanel.add(jlNumScen);
filterPanel.add(numScenPanel);
jpText = new JPanel();
jpText.setBorder(BorderFactory.createTitledBorder("Filter"));
jpText.setLayout(new BoxLayout(jpText, BoxLayout.Y_AXIS));
//jpText.setLayout(new GridLayout(3, 1));
JPanel jpTextField = new JPanel(new GridLayout(3, 1));
jtText = new JTextField(" ");
jtText.setMinimumSize(new Dimension(200, 25));
jtText.setMaximumSize(new Dimension(32000, 25));
jtText.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
filterText = jtText.getText().toLowerCase();
filterScenarioList();
}
public void insertUpdate(DocumentEvent e) {
filterText = jtText.getText().toLowerCase();
filterScenarioList();
}
public void changedUpdate(DocumentEvent e) {
filterText = jtText.getText().toLowerCase();
filterScenarioList();
}
});
jpTextField.add(jtText);
//jpText.add(jtText); //jpTextField);
JPanel pOff = new JPanel();
pOff.setLayout(new BoxLayout(pOff, BoxLayout.Y_AXIS));
pOff.setMaximumSize(new Dimension(32000, 24));
jcOfficialScenarios = new JCheckBox("Official Scenarios");
// jcOfficialScenarios.setSelected(true);
jcOfficialScenarios.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterOfficial = jcOfficialScenarios.isSelected();
filterScenarioList();
}
});
//pOff.add(jcOfficialScenarios);
//jpText.add(jcOfficialScenarios); //pOff);
jpTextField.add(jcOfficialScenarios);
pOff = new JPanel();
pOff.setLayout(new BoxLayout(pOff, BoxLayout.Y_AXIS));
pOff.setMaximumSize(new Dimension(32000, 24));
jcSFTF = new JCheckBox("SFTF (Unofficial)");
// jcSFTF.setSelected(true);
jcSFTF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterSFTF = jcSFTF.isSelected();
filterScenarioList();
}
});
//pOff.add(jcSFTF);
//jpText.add(jcSFTF); //pOff);
jpTextField.add(jcSFTF);
jpText.add(jpTextField);
jpText.add(Box.createVerticalGlue());
filterPanel.add(jpText);
jpFront = new JPanel();
jpFront.setBorder(BorderFactory.createTitledBorder("Front"));
jpFront.setLayout(new BoxLayout(jpFront, BoxLayout.Y_AXIS));
jcFront = new JCheckBox[frontNames.length];
for (int i = 0; i < frontNames.length; i++) {
final int j = i;
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setMaximumSize(new Dimension(32000, 24));
jcFront[i] = new JCheckBox(frontNames[i]);
// jcFront[i].setSelected(true);
// filterFronts[i] = true;
jcFront[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterFronts[j] = jcFront[j].isSelected();
filterScenarioList();
}
});
p.add(jcFront[i]);
jpFront.add(p);
}
filterPanel.add(jpFront);
jpExpansions = new JPanel();
jpExpansions.setBorder(BorderFactory.createTitledBorder("Series")); // Expansions
jpExpansions.setLayout(new BoxLayout(jpExpansions, BoxLayout.Y_AXIS));
jcExpansions = new JComboBox(expansionMenu);
jcExpansions.setEditable(false);
jcExpansions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int idx = jcExpansions.getSelectedIndex();
for (int i = 0; i < filterExpansions.length; i++)
filterExpansions[i] = ((idx-1) == i);
filterScenarioList();
}
});
jpExpansions.add(jcExpansions);
filterPanel.add(jpExpansions);
jpType = new JPanel();
jpType.setBorder(BorderFactory.createTitledBorder("Type"));
jpType.setLayout(new BoxLayout(jpType, BoxLayout.Y_AXIS));
jcType = new JCheckBox[typeNames.length];
for (int i = 0; i < typeNames.length; i++) {
final int j = i;
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setMaximumSize(new Dimension(32000, 24));
jcType[i] = new JCheckBox(typeNames[i]);
// jcType[i].setSelected(true);
// filterTypes[i] = true;
jcType[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterTypes[j] = jcType[j].isSelected();
filterScenarioList();
}
});
p.add(jcType[i]);
jpType.add(p);
}
filterPanel.add(jpType);
jpYear = new JPanel();
jpYear.setBorder(BorderFactory.createTitledBorder("Year"));
jpYear.setLayout(new BoxLayout(jpYear, BoxLayout.Y_AXIS));
jcYear = new JCheckBox[yearNames.length];
for (int i = 0; i < yearNames.length; i++) {
final int j = i;
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setMaximumSize(new Dimension(32000, 24));
jcYear[i] = new JCheckBox(yearNames[i]);
// jcYear[i].setSelected(true);
// filterYears[i] = true;
jcYear[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterYears[j] = jcYear[j].isSelected();
filterScenarioList();
}
});
p.add(jcYear[i]);
jpYear.add(p);
}
filterPanel.add(jpYear);
filterPanel.add(Box.createVerticalGlue());
JScrollPane filterScroller = new JScrollPane(filterPanel);
filterScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
filterScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scenarioModel = new ScenarioTableModel();
scenarioList = new JTable(scenarioModel);
filterScenarioList();
JTableHeader header = scenarioList.getTableHeader();
header.setUpdateTableInRealTime(true);
header.addMouseListener(scenarioModel.new ColumnListener(scenarioList));
header.setReorderingAllowed(true);
scenarioList.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
"pressSelectScenario");
scenarioList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int row = scenarioList.getSelectedRow();
String imageName = "";
if (row >= 0)
{
// load preview pane image
M44Setup setup = scenarioModel.getRow(row);
if (setup.fileName != null)
{
if (!setup.classified)
imageName = scenarioModel.getRow(row).getAttributeValueString(M44Setup.FILE) + ".jpg";
else
imageName = "mm_classified.jpg";
}
}
if (imageName.length() > 0)
previewImage = Op.load(imageName).getImage();
else
previewImage = null;
previewPane.repaint();
}
});
scenarioList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = ((JTable) e.getSource()).getSelectedRow();
M44Setup setup = scenarioModel.getRow(row);
launchSetup(setup);
}
}
});
int[] widths = {85, 0, 0, 0, 105, 70, 0, 120, 105};
for (int i = 0; i < widths.length; i++)
if (widths[i] > 0) {
scenarioList.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
scenarioList.getColumnModel().getColumn(i).setMaxWidth(widths[i]);
}
scenarioList.getColumnModel().getColumn(1).setMinWidth(250);
JScrollPane scScenarioList = new JScrollPane(scenarioList);
//listPanel.add(scScenarioList, BorderLayout.CENTER);
viewOnlineButton = new JButton("View Online");
viewOnlineButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pressViewOnline();
}
});
randomButton = new JButton("Pick Random");
randomButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pressRandomScenario();
}
});
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
thisFrame.dispose();
}
});
selectButton = new JButton("Load");
selectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pressSelectScenario();
}
});
selectButton.setDefaultCapable(true);
//selectButton.setEnabled(!GameModule.getGameModule().getGameState().isGameStarted());
JButton btCheckNone = new JButton("Select None");
btCheckNone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < frontNames.length; i++)
if (jcFront[i].isSelected()) {
jcFront[i].setSelected(false);
filterFronts[i] = false;
}
for (int i = 0; i < typeNames.length; i++)
if (jcType[i].isSelected()) {
jcType[i].setSelected(false);
filterTypes[i] = false;
}
for (int i = 0; i < filterExpansions.length; i++)
//if (jcExpansions[i].isSelected()) {
// jcExpansions[i].setSelected(false);
filterExpansions[i] = false;
jcExpansions.setSelectedIndex(0);
for (int i = 0; i < yearNames.length; i++)
if (jcYear[i].isSelected()) {
jcYear[i].setSelected(false);
filterYears[i] = false;
}
filterScenarioList();
}
});
JButton btCheckAll = new JButton("Select All");
btCheckAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < frontNames.length; i++)
if (!jcFront[i].isSelected()) {
jcFront[i].setSelected(true);
filterFronts[i] = true;
}
for (int i = 0; i < typeNames.length; i++)
if (!jcType[i].isSelected()) {
jcType[i].setSelected(true);
filterTypes[i] = true;
}
for (int i = 0; i < filterExpansions.length; i++)
//if (!jcExpansions[i].isSelected()) {
//jcExpansions[i].setSelected(true);
filterExpansions[i] = false; //true;
jcExpansions.setSelectedIndex(0);
for (int i = 0; i < yearNames.length; i++)
if (!jcYear[i].isSelected()) {
jcYear[i].setSelected(true);
filterYears[i] = true;
}
filterScenarioList();
}
});
buttonPanel.add(btCheckNone);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(btCheckAll);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(viewOnlineButton);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(randomButton);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(cancelButton);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(selectButton);
previewPanel = new JPanel(new BorderLayout());
previewPanel.setBorder(BorderFactory.createTitledBorder("Preview"));
previewPane = new JComponent() {
@Override
public void paintComponent(Graphics g) {
if (previewImage != null) {
int h = previewImage.getHeight(null);
int w = previewImage.getWidth(null);
int ph = this.getHeight();
double ratio = (double)ph / (double)h;
int nh = ph > h ? h : ph;
int nw = ph > h ? w : (int)Math.round((double)w * ratio);
g.drawImage(previewImage, 0, 0, nw, nh, null);
}
}
};
previewPane.setPreferredSize(new Dimension(1500, 500));
previewPane.setMinimumSize(new Dimension(350, 250));
previewPane.setMaximumSize(new Dimension(1500,500));
//previewPanel.add(previewPane, BorderLayout.CENTER);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scScenarioList, previewPane);
splitPane.setOneTouchExpandable(false);
//listPanel.add(previewPanel, BorderLayout.SOUTH);
//mainPanel.add(listPanel, BorderLayout.CENTER);
mainPanel.add(splitPane, BorderLayout.CENTER);
mainPanel.add(filterScroller, BorderLayout.WEST);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
thisFrame.getContentPane().add(mainPanel, BorderLayout.CENTER);
thisFrame.getRootPane().setDefaultButton(selectButton);
jtText.setText("");
splitPane.setDividerLocation((height < 1050) ? height - 340 : height - 590);
}
protected void pressSelectScenario() {
int row = scenarioList.getSelectedRow();
if (row >= 0)
launchSetup(scenarioModel.getRow(row));
}
protected void filterScenarioList() {
Vector<M44Setup> list = new Vector<M44Setup>();
boolean doOriginFilter = (filterOfficial || filterSFTF);
boolean doFrontFilter = false;
for (int j = 0; j < frontNames.length; j++)
if (filterFronts[j] == true)
doFrontFilter = true;
boolean doExpansionFilter = false;
for (int j = 0; j < series.size(); j++)
if (filterExpansions[j] == true)
doExpansionFilter = true;
boolean doTypeFilter = false;
for (int j = 0; j < typeNames.length; j++)
if (filterTypes[j] == true)
doTypeFilter = true;
boolean doYearFilter = false;
for (int j = 0; j < yearNames.length; j++)
if (filterYears[j] == true)
doYearFilter = true;
// boolean doFrontFilter = true;
// boolean doExpansionFilter = true;
// boolean doTypeFilter = true;
// boolean doYearFilter = true;
for (int i = 0; i < setups.size(); i++) {
M44Setup item = setups.get(i);
String frontName = item.front;
String yearName = item.year;
String typeName = item.scentype;
String preCode = "";
if (item.m44code.length() >= 2)
preCode = item.m44code.substring(0, 2);
String errorLogPath =
new File(Info.getConfDir(), "errorLog").getAbsolutePath();
boolean isAirPack = false;
if (preCode.equals("AW") || preCode.equals("AE") || preCode.equals("AM") || preCode.equals("AP"))
isAirPack = true;
boolean filterAirPack = false;
boolean isOfficial = false;
if (item.official != null)
isOfficial = item.official;
boolean found = false;
for (int j = 0; j < frontNames.length; j++)
if (frontNames[j].equals(frontName))
found = true;
// No "Other" Front
//if (!found)
// frontName = frontNames[frontNames.length-1];
found = false;
for (int j = 0; j < series.size(); j++) {
M44Series serie = series.get(j);
// if (preCode == "DY")
// FileWriter out;
// try {
// out = new FileWriter(errorLogPath, true);
// out.write((j+1) + ". CODE = " + serie.prefix + " == " + preCode + "\n");
// out.close();
// } catch (IOException e) {
// JOptionPane.showMessageDialog(null, e.getMessage());
// e.printStackTrace();
if (serie.prefix.equals(preCode))
found = true;
}
if (!found)
if (preCode.length() >= 1 && preCode.substring(0, 1).equals("A"))
filterAirPack = true;
else
preCode = "";
found = false;
yearName = "19"+yearName;
for (int j = 0; j < yearNames.length; j++)
if (yearNames[j].equals(yearName))
found = true;
// No "Other" year
//if (!found)
// yearName = yearNames[yearNames.length-1];
boolean keepItem = true;
if (doOriginFilter && isOfficial && !filterOfficial)
keepItem = false;
if (doOriginFilter && !isOfficial && !filterSFTF)
keepItem = false;
if (keepItem && doFrontFilter) {
keepItem = false;
for (int j = 0; j < frontNames.length; j++)
if ((frontNames[j].equals(frontName)) && (filterFronts[j] == true))
keepItem = true;
}
if (keepItem && doExpansionFilter) {
keepItem = false;
if (filterAirPack && filterExpansions[indexAirPackExpansion] == true) {
if (isAirPack)
keepItem = true;
} else {
for (int j = 0; j < series.size(); j++)
if ((series.get(j).prefix.equals(preCode)) && (filterExpansions[j] == true))
keepItem = true;
}
}
if (keepItem)
if (doTypeFilter) {
keepItem = false;
String[] breaklordArray = {"OT-Inland", "OT-Beach", "OT-Winter", "OT-Desert"};
for (int j = 0; j < typeNames.length; j++)
{
if ((typeNames[j].equals(typeName)) && (filterTypes[j] == true))
keepItem = true;
if ((typeNames[j].equals(breaklordLabel)) && (filterTypes[j] == true))
{
for (int k = 0; k < breaklordArray.length; k++)
if ((breaklordArray[k].equals(typeName)))
keepItem = true;
}
}
}
if (keepItem)
if (doYearFilter) {
keepItem = false;
for (int j = 0; j < yearNames.length; j++)
if ((yearNames[j].equals(yearName)) && (filterYears[j] == true))
keepItem = true;
}
if (keepItem)
if (filterText.length() > 0) {
keepItem = false;
String name = item.getConfigureName();
String set = "";
if (item.set != null) set = item.set;
String tournament = "";
if (item.tournament != null) tournament = item.tournament;
String operation = ""; if (item.operation != null) operation = item.operation;
String author = ""; if (item.author != null) author = item.author;
if (name.toLowerCase().indexOf(filterText) >= 0) keepItem = true;
if (tournament.toLowerCase().indexOf(filterText) >= 0) keepItem = true;
if (set.toLowerCase().indexOf(filterText) >= 0) keepItem = true;
if (operation.toLowerCase().indexOf(filterText) >= 0) keepItem = true;
if (author.toLowerCase().indexOf(filterText) >= 0) keepItem = true;
}
if (keepItem)
list.add(item);
}
scenarioModel.setData(list);
scenarioModel.sortData(scenarioList);
jlNumScen.setText("" + list.size() + " of " + setups.size());
}
protected void pressViewOnline() {
int row = scenarioList.getSelectedRow();
if (row >= 0)
{
M44Setup scen = scenarioModel.getRow(row);
if (scen.dowid != "")
{
try {
openWebpage(new URL("https:
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
try {
openWebpage(new URL("https:
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected void pressRandomScenario() {
Random r = new Random();
int max = scenarioModel.getRowCount();
int choice = r.nextInt(max);
scenarioList.getSelectionModel().setSelectionInterval(choice, choice);
scenarioList.scrollRectToVisible(new Rectangle(scenarioList.getCellRect(choice, 0, true)));
}
protected void launchSetup(M44Setup setup) {
if (setup.classified)
JOptionPane.showMessageDialog(null, "This scenario can not be loaded because it is classified.\n\nClassified scenarios are usually official scenarios published in\nprint but not on the Web. This is why their content is not\ndisplayed. However, you may still rate them and write After\nAction Reports.", "Classified Scenario", JOptionPane.INFORMATION_MESSAGE);
else
if (setup.launch())
thisFrame.dispose();
}
private class ScenarioTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private Vector<M44Setup> data = new Vector<M44Setup>();
private String[] columnNames = {"Type", "Title", "Set", "Tournament", "Front", "Date", "Operation", "Author", "Code"};
protected int sortCol = 1;
protected boolean isSortAsc = true;
protected boolean sortByID = false;
public void setData(Vector<M44Setup> newData) {
data.clear();
data = newData;
fireTableDataChanged();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return 9;
}
public int getRowCount() {
return data.size();
}
public M44Setup getRow(int row) {
return data.get(row);
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return data.get(row).scentype;
case 1:
String name = data.get(row).getConfigureName();
// if (data.get(row).airpack)
// name += " [AIR PACK]";
return name;
case 2:
if ((data.get(row).set == null) || (data.get(row).set.length() == 0))
return "";
else
return data.get(row).set;
case 3:
if ((data.get(row).tournament == null) || (data.get(row).tournament.length() == 0))
return "";
else
return data.get(row).tournament;
case 4:
return data.get(row).front;
case 5:
return data.get(row).getDate();
case 6:
return data.get(row).operation;
case 7:
return data.get(row).author;
case 8:
String code = "";
if (data.get(row).m44code != null)
code = data.get(row).m44code;
String dow = "";
if (data.get(row).dowid != null)
dow = data.get(row).dowid;
if ((code.length() > 0) && (dow.length() > 0)) {
code = code + " #" + dow;
} else if (dow.length() > 0)
code = "#" + dow;
return code;
default:
return "";
}
}
public void sortData(JTable table) {
Collections.sort(data,new MyComparator(isSortAsc, sortCol));
table.tableChanged(new TableModelEvent(ScenarioTableModel.this));
table.repaint();
}
class ColumnListener extends MouseAdapter {
protected JTable table;
public ColumnListener(JTable t) {
table = t;
}
public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = scenarioList.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex)
.getModelIndex();
if (modelIndex < 0)
return;
if (sortCol == modelIndex) {
if ((sortCol == 8) && !isSortAsc)
sortByID = !sortByID;
isSortAsc = !isSortAsc;
} else {
sortCol = modelIndex;
isSortAsc = true;
sortByID = false;
}
for (int i = 0; i < getColumnCount(); i++) {
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
table.getTableHeader().repaint();
sortData(table);
}
}
class MyComparator implements Comparator<M44Setup> {
protected boolean isSortAsc;
protected int col;
public MyComparator(boolean sortAsc, int col) {
this.isSortAsc = sortAsc;
this.col = col;
}
public int compare(M44Setup o1, M44Setup o2) {
int result = 0;
try {
switch (col) {
case 0:
result = getScenTypeNumeric(o1.scentype) - getScenTypeNumeric(o2.scentype);
break;
case 1:
result = o1.getConfigureName().compareTo(o2.getConfigureName()); break;
case 2:
String set1 = "";
String set2 = "";
if (o1.set != null)
set1 = o1.set;
if (o2.set != null)
set2 = o2.set;
result = set1.compareTo(set2); break;
case 3:
String tournament1 = "";
String tournament2 = "";
if (o1.tournament != null)
tournament1 = o1.tournament;
if (o2.tournament != null)
tournament2 = o2.tournament;
result = tournament1.compareTo(tournament2); break;
case 4:
int f1 = getFrontNumeric(o1.front);
int f2 = getFrontNumeric(o2.front);
result = f1 - f2;
break;
case 5:
result = o1.year.compareTo(o2.year);
if (result == 0) {
int m1 = getNumericMonth(o1.month);
int m2 = getNumericMonth(o2.month);
result = m1 - m2;
}
break;
case 6:
result = o1.operation.compareTo(o2.operation); break;
case 7:
if (o1.author == "" && o2.author != "")
result = 1;
else if (o1.author != "" && o2.author == "")
result = -1;
else
result = o1.author.toLowerCase().compareTo(o2.author.toLowerCase());
break;
case 8:
String code1 = o1.m44code;
String code2 = o2.m44code;
int c1 = code1.length();
int c2 = code2.length();
if (!sortByID && ((c1 != 0) && (c2 != 0)))
result = code1.compareTo(code2);
else if (!sortByID && ((c1 != 0) && (c2 == 0)))
result = -1;
else if (!sortByID && ((c1 == 0) && (c2 != 0)))
result = 1;
else {
try {
c1 = Integer.parseInt(o1.dowid);
} catch (NumberFormatException ex) {
c1 = 99999999;
}
try {
c2 = Integer.parseInt(o2.dowid);
} catch (NumberFormatException ex) {
c2 = 99999999;
}
result = c1 - c2;
}
break;
}
} catch (NullPointerException ex) {
}
if (!isSortAsc)
result = -result;
return result;
}
private int getFrontNumeric(String front) {
int value = 999;
for (int i = 0; i < frontNames.length; i++)
if (front.equals(frontNames[i]))
value = i;
return value;
}
public boolean equals(Object obj) {
if (obj instanceof MyComparator) {
MyComparator compObj = (MyComparator) obj;
return compObj.isSortAsc == isSortAsc;
}
return false;
}
public int getScenTypeNumeric(String scentype) {
int value = 999;
for (int i = 0; i < typeNames.length; i++)
if (scentype.equals(typeNames[i]))
value = i;
return value;
}
public int getNumericMonth(String month) {
int value = 999;
for (int i = 0; i < monthNames.length; i++)
if (month.equals(monthNames[i]))
value = i;
return value;
}
}
}
public class URLCellRenderer extends JLabel implements TableCellRenderer {
// This method is called each time a cell in a column
// using this renderer needs to be rendered.
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
// 'value' is value contained in the cell located at
// (rowIndex, vColIndex)
setForeground(new Color(0, 0, 255));
if (isSelected) {
// cell (and perhaps other cells) are selected
}
if (hasFocus) {
// this cell is the anchor and the table has the focus
}
// Configure the component with the specified value
setText(value.toString());
// Set tool tip if desired
setToolTipText((String)value);
// Since the renderer is a component, return itself
return this;
}
// The following methods override the defaults for performance reasons
public void validate() {}
public void revalidate() {}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
}
}
|
package com.exedio.cope;
import java.io.File;
import java.util.Arrays;
import com.exedio.cope.testmodel.AttributeItem;
import com.exedio.cope.util.ReactivationConstructorDummy;
/**
* Tests the model itself, without creating/using any persistent data.
* @author Ralf Wiebicke
*/
public class ModelTest extends TestmodelTest
{
public void testSupportsReadCommitted()
{
assertEquals( true, model.hasCurrentTransaction() );
if ( model.getDatabase().getClass().getName().equals("com.exedio.cope.HsqldbDatabase") )
{
assertEquals( false, model.supportsReadCommitted() );
}
else if ( model.getDatabase().getClass().getName().equals("com.exedio.cope.OracleDatabase") )
{
assertEquals( true, model.supportsReadCommitted() );
}
else if ( model.getDatabase().getClass().getName().equals("com.exedio.cope.MysqlDatabase") )
{
assertEquals( true, model.supportsReadCommitted() );
}
else
{
fail( model.getDatabase().getClass().getName() );
}
}
public static final void assertEquals(final String expected, final String actual)
{
assertEquals("
}
public void testSetPropertiesInitially()
{
final Properties mp = model.getProperties();
final Properties defaultProps = getProperties();
model.setPropertiesInitially(defaultProps);
// TODO: use an extra model for the model test, then the following code can be removed
final String defaultSource = defaultProps.getSource();
final int defaultSourceSpace = defaultSource.indexOf(' ');
final File file = new File(defaultSource.substring(0, defaultSourceSpace));
final java.util.Properties newProps = Properties.loadProperties(file);
newProps.setProperty("database.forcename.StringItem", "STRINGITEMS");
newProps.setProperty("database.forcename.STRINGITEMS.this", "STRINGITEM_ID");
newProps.setProperty("database.forcename.STRINGITEMS.any", "ANY");
newProps.setProperty("database.forcename.STRINGITEMS.mandatory", "MANDATORY");
newProps.setProperty("database.forcename.STRINGITEMS.min4", "MIN_4");
newProps.setProperty("database.forcename.STRINGITEMS.max4", "MAX_4");
newProps.setProperty("database.forcename.STRINGITEMS.min4Max8", "MIN4_MAX8");
newProps.setProperty("database.forcename.STRINGITEMS.exact6", "EXACT_6");
newProps.setProperty("database.forcename.ItemWithSingleUnique", "UNIQUE_ITEMS");
newProps.setProperty("database.forcename.UNIQUE_ITEMS.this", "UNIQUE_ITEM_ID");
newProps.setProperty("database.forcename.UNIQUE_ITEMS.uniqueString", "UNIQUE_STRING");
newProps.setProperty("database.forcename.UNIQUE_ITEMS.otherString", "OTHER_STRING");
newProps.setProperty("database.forcename.ItemWithSingleUnique_uniqueString_Unq", "IX_ITEMWSU_US");
{
final java.util.Properties props = (java.util.Properties)newProps.clone();
props.setProperty(Properties.DATABASE_URL, "zack");
final String source = file.getAbsolutePath()+'/'+Properties.DATABASE_URL+"=zack";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
assertEquals(
"inconsistent initialization for " + Properties.DATABASE_URL +
" between " + mp.getSource() + " and " + source +
", expected " + mp.getDatabaseUrl() +
" but got zack.", e.getMessage());
}
}
{
final java.util.Properties props = (java.util.Properties)newProps.clone();
props.setProperty(Properties.DATABASE_USER, "zick");
final String source = file.getAbsolutePath()+'/'+Properties.DATABASE_USER+"=zick";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
assertEquals(
"inconsistent initialization for " + Properties.DATABASE_USER +
" between " + mp.getSource() + " and " + source +
", expected "+mp.getDatabaseUser()+" but got zick.", e.getMessage());
}
}
{
final java.util.Properties props = (java.util.Properties)newProps.clone();
props.setProperty(Properties.DATABASE_PASSWORD, "zock");
final String source = file.getAbsolutePath()+'/'+Properties.DATABASE_PASSWORD+"=zock";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
// dont put password into exception message
assertEquals(
"inconsistent initialization for " + Properties.DATABASE_PASSWORD +
" between " + mp.getSource() + " and " + source, e.getMessage());
}
}
{
final java.util.Properties props = (java.util.Properties)newProps.clone();
final String newValue = mp.getDatabaseDontSupportEmptyStrings()?"false":"true";
props.setProperty(Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS, newValue);
final String source = file.getAbsolutePath()+'/'+Properties.DATABASE_PASSWORD+"=zock";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
assertEquals(
"inconsistent initialization for " + Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS +
" between " + mp.getSource() + " and " + source +
", expected " + mp.getDatabaseDontSupportEmptyStrings() +
" but got " + newValue + ".", e.getMessage());
}
props.setProperty(Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS, "True");
try
{
new Properties(props, "sourceTrue");
}
catch(RuntimeException e)
{
assertEquals(
"property " + Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS + " in sourceTrue has invalid value," +
" expected >true< or >false< bot got >True<.", e.getMessage());
}
props.setProperty(Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS, "falsE");
try
{
new Properties(props, "sourcefalsE");
}
catch(RuntimeException e)
{
assertEquals(
"property " + Properties.DATABASE_DONT_SUPPORT_EMPTY_STRINGS + " in sourcefalsE has invalid value," +
" expected >true< or >false< bot got >falsE<.", e.getMessage());
}
}
{
final char SEP = File.separatorChar;
final java.util.Properties props = (java.util.Properties)newProps.clone();
props.setProperty(Properties.DATADIR_PATH, props.getProperty(Properties.DATADIR_PATH)+SEP+"AttributeItem");
final String source = file.getAbsolutePath()+'/'+Properties.DATADIR_PATH+"=/AttributeItem";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
assertEquals(
"inconsistent initialization for " + Properties.DATADIR_PATH +
" between " + mp.getSource() + " and " + source +
", expected " + mp.getDatadirPath() + " but got " + mp.getDatadirPath() + SEP + "AttributeItem.", e.getMessage());
}
}
{
final java.util.Properties props = (java.util.Properties)newProps.clone();
props.setProperty(Properties.MEDIA_ROOT_URL, "zosch");
final String source = file.getAbsolutePath()+'/'+Properties.MEDIA_ROOT_URL+"=zosch";
try
{
model.setPropertiesInitially(new Properties(props, source));
}
catch(RuntimeException e)
{
assertEquals(
"inconsistent initialization for " + Properties.MEDIA_ROOT_URL +
" between " + mp.getSource() + " and " + source +
", expected " + mp.getMediaRootUrl() +
" but got zosch.", e.getMessage());
}
props.remove(Properties.MEDIA_ROOT_URL);
assertEquals(Properties.MEDIA_ROOT_URL_DEFAULT, new Properties(props, "source").getMediaRootUrl());
props.setProperty(Properties.MEDIA_ROOT_URL, "klack");
assertEquals("klack", new Properties(props, "source").getMediaRootUrl());
}
}
public void testType()
{
final AttributeItem item = null;
assertEquals(false, item.MANDATORY.readOnly);
assertEquals(false, item.MANDATORY.unique);
assertEquals(true, item.MANDATORY.mandatory);
assertEquals(false, item.OPTIONAL.readOnly);
assertEquals(false, item.OPTIONAL.unique);
assertEquals(false, item.OPTIONAL.mandatory);
assertEquals(false, item.UNIQUE.readOnly);
assertEquals(true, item.UNIQUE.unique);
assertEquals(true, item.UNIQUE.mandatory);
assertEquals(false, item.UNIQUE_OPTIONAL.readOnly);
assertEquals(true, item.UNIQUE_OPTIONAL.unique);
assertEquals(false, item.UNIQUE_OPTIONAL.mandatory);
assertEquals(true, item.READ_ONLY.readOnly);
assertEquals(false, item.READ_ONLY.unique);
assertEquals(true, item.READ_ONLY.mandatory);
assertEquals(true, item.READ_ONLY_OPTIONAL.readOnly);
assertEquals(false, item.READ_ONLY_OPTIONAL.unique);
assertEquals(false, item.READ_ONLY_OPTIONAL.mandatory);
assertEquals(true, item.READ_ONLY_UNIQUE.readOnly);
assertEquals(true, item.READ_ONLY_UNIQUE.unique);
assertEquals(true, item.READ_ONLY_UNIQUE.mandatory);
assertEquals(true, item.READ_ONLY_UNIQUE_OPTIONAL.readOnly);
assertEquals(true, item.READ_ONLY_UNIQUE_OPTIONAL.unique);
assertEquals(false, item.READ_ONLY_UNIQUE_OPTIONAL.mandatory);
assertEquals(AttributeItem.class, item.TYPE.getJavaClass());
assertEquals(item.TYPE, Type.findByJavaClass(AttributeItem.class));
try
{
Type.findByJavaClass(ModelTest.class);
fail("should have thrown RuntimeException");
}
catch(RuntimeException e)
{
assertEquals("there is no type for class com.exedio.cope.ModelTest", e.getMessage());
}
assertEquals(item.TYPE, model.findTypeByID(item.TYPE.getID()));
final Attribute[] attributes = new Attribute[]{
item.someString,
item.someNotNullString,
item.someInteger,
item.someNotNullInteger,
item.someLong,
item.someNotNullLong,
item.someDouble,
item.someNotNullDouble,
item.someDate,
item.someLongDate,
item.day,
item.someBoolean,
item.someNotNullBoolean,
item.someItem,
item.someNotNullItem,
item.someEnum,
item.someNotNullEnum,
item.someData.getData(),
item.someData.getMimeMajor(),
item.someData.getMimeMinor(),
};
assertEqualsUnmodifiable(Arrays.asList(attributes), item.TYPE.getAttributes());
assertEqualsUnmodifiable(Arrays.asList(attributes), item.TYPE.getDeclaredAttributes());
final Feature[] features = new Feature[]{
item.someString,
item.someStringUpperCase,
item.someStringLength,
item.someNotNullString,
item.someInteger,
item.someNotNullInteger,
item.someLong,
item.someNotNullLong,
item.someDouble,
item.someNotNullDouble,
item.someDate,
item.someLongDate,
item.day,
item.someBoolean,
item.someNotNullBoolean,
item.someItem,
item.someNotNullItem,
item.someEnum,
item.someNotNullEnum,
item.someData,
item.someData.getData(),
item.someData.getMimeMajor(),
item.someData.getMimeMinor(),
item.emptyItem,
};
assertEqualsUnmodifiable(Arrays.asList(features), item.TYPE.getFeatures());
assertEqualsUnmodifiable(Arrays.asList(features), item.TYPE.getDeclaredFeatures());
assertEquals(item.someString, item.TYPE.getFeature("someString"));
assertEquals(item.someStringUpperCase, item.TYPE.getFeature("someStringUpperCase"));
try
{
new Type(NoCreationConstructor.class);
fail();
}
catch(NestingRuntimeException e)
{
assertEquals(
NoCreationConstructor.class.getName() +
" does not have a creation constructor:" + NoCreationConstructor.class.getName() +
".<init>([L" + AttributeValue.class.getName() + ";)", e.getMessage());
assertEquals(NoSuchMethodException.class, e.getNestedCause().getClass());
}
try
{
new Type(NoReactivationConstructor.class);
fail();
}
catch(NestingRuntimeException e)
{
assertEquals(e.getMessage(),
NoReactivationConstructor.class.getName() +
" does not have a reactivation constructor:" + NoReactivationConstructor.class.getName() +
".<init>(" + ReactivationConstructorDummy.class.getName() + ", int)", e.getMessage());
assertEquals(NoSuchMethodException.class, e.getNestedCause().getClass());
}
}
static class NoCreationConstructor extends Item
{
NoCreationConstructor()
{
super(null);
}
}
static class NoReactivationConstructor extends Item
{
NoReactivationConstructor(final AttributeValue[] initialAttributes)
{
super(null);
}
}
}
|
package jolie.lang.parse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import jolie.lang.NativeType;
/**
* Scanner implementation for the Jolie language parser.
*
* @author Fabrizio Montesi
*
*/
public class Scanner
{
/** Token types */
public enum TokenType {
EOF, ///< End Of File
ID, ///< [a-z][a-zA-Z0-9]*
COMMA,
DOT,
INT,
TRUE, ///< true
FALSE, ///< false
LONG, ///< [0-9]+(l|L)
DOUBLE, ///< [0-9]*"."[0-9]+(e|E)[0-9]+
LPAREN,
RPAREN,
LSQUARE,
RSQUARE,
LCURLY,
RCURLY,
//DOLLAR, ///< $
STRING, ///< "[[:graph:]]*"
INCREMENT,
MINUS, ///< The minus sign -
ASTERISK,
DIVIDE,
ASSIGN,
PLUS,
ADD_ASSIGN,
MINUS_ASSIGN,
MULTIPLY_ASSIGN,
DIVIDE_ASSIGN,
SEQUENCE,
IF,
ELSE, ///< else
LANGLE,
RANGLE,
AT,
LINKIN, ///< linkIn
LINKOUT, ///< linkOut
INSTANCE_OF, ///< instanceof
EQUAL,
AND,
OR,
PARALLEL,
NOT,
CARET,
COLON,
OP_OW, ///< OneWay
OP_RR, ///< RequestResponse
DEFINE, ///< define
MAJOR_OR_EQUAL,
MINOR_OR_EQUAL,
NOT_EQUAL,
NULL_PROCESS, ///< nullProcess
WHILE, ///< while
EXECUTION, ///< execution
THROW, ///< throw
DOCUMENTATION_COMMENT,
INSTALL, ///< install
SCOPE, ///< scope
SPAWN, ///< spawn
THIS, ///< this
COMPENSATE, ///< comp
EXIT, ///< exit
INCLUDE, ///< include
CONSTANTS, ///< constants
POINTS_TO,
QUESTION_MARK,
ARROW,
DEEP_COPY_LEFT,
RUN, ///< run
UNDEF, ///< undef
HASH, ///<
PERCENT_SIGN,
FOR, ///< for
FOREACH, ///< foreach
WITH, ///< with
DECREMENT,
IS_STRING, ///< is_string
IS_INT, ///< is_int
IS_DOUBLE, ///< is_double
IS_BOOL, ///< is_bool
IS_LONG, ///< is_long
IS_DEFINED, ///< is_defined
CAST_INT, ///< int
CAST_STRING, ///< string
CAST_DOUBLE, ///< double
CAST_BOOL, ///< bool
CAST_LONG, ///< long
SYNCHRONIZED, ///< synchronized
THROWS, ///< throws
CURRENT_HANDLER,
INIT, ///< init
PROVIDE, ///< provide
ERROR ///< Scanner error
}
/*
* Map of unreserved keywords,
* which can be considered as IDs in certain places (e.g. variables).
*/
private static final Map< String, TokenType > unreservedKeywords = new HashMap< String, TokenType >();
static {
// Initialise the unreserved keywords map.
unreservedKeywords.put( "OneWay", TokenType.OP_OW );
unreservedKeywords.put( "RequestResponse", TokenType.OP_RR );
unreservedKeywords.put( "linkIn", TokenType.LINKIN );
unreservedKeywords.put( "linkOut", TokenType.LINKOUT );
unreservedKeywords.put( "if", TokenType.IF );
unreservedKeywords.put( "else", TokenType.ELSE );
unreservedKeywords.put( "include", TokenType.INCLUDE );
unreservedKeywords.put( "define", TokenType.DEFINE );
unreservedKeywords.put( "nullProcess", TokenType.NULL_PROCESS );
unreservedKeywords.put( "while", TokenType.WHILE );
unreservedKeywords.put( "execution", TokenType.EXECUTION );
unreservedKeywords.put( "install", TokenType.INSTALL );
unreservedKeywords.put( "this", TokenType.THIS );
unreservedKeywords.put( "synchronized", TokenType.SYNCHRONIZED );
unreservedKeywords.put( "throw", TokenType.THROW );
unreservedKeywords.put( "scope", TokenType.SCOPE );
unreservedKeywords.put( "spawn", TokenType.SPAWN );
unreservedKeywords.put( "comp", TokenType.COMPENSATE );
unreservedKeywords.put( "exit", TokenType.EXIT );
unreservedKeywords.put( "constants", TokenType.CONSTANTS );
unreservedKeywords.put( "undef", TokenType.UNDEF );
unreservedKeywords.put( "for", TokenType.FOR );
unreservedKeywords.put( "foreach", TokenType.FOREACH );
unreservedKeywords.put( "is_defined", TokenType.IS_DEFINED );
unreservedKeywords.put( "is_string", TokenType.IS_STRING );
unreservedKeywords.put( "is_int", TokenType.IS_INT );
unreservedKeywords.put( "is_bool", TokenType.IS_BOOL );
unreservedKeywords.put( "is_long", TokenType.IS_LONG );
unreservedKeywords.put( "is_double", TokenType.IS_DOUBLE );
unreservedKeywords.put( "instanceof", TokenType.INSTANCE_OF );
unreservedKeywords.put( NativeType.INT.id(), TokenType.CAST_INT );
unreservedKeywords.put( NativeType.STRING.id(), TokenType.CAST_STRING );
unreservedKeywords.put( NativeType.BOOL.id(), TokenType.CAST_BOOL );
unreservedKeywords.put( NativeType.DOUBLE.id(), TokenType.CAST_DOUBLE );
unreservedKeywords.put( NativeType.LONG.id(), TokenType.CAST_LONG );
unreservedKeywords.put( "throws", TokenType.THROWS );
unreservedKeywords.put( "cH", TokenType.CURRENT_HANDLER );
unreservedKeywords.put( "init", TokenType.INIT );
unreservedKeywords.put( "with", TokenType.WITH );
unreservedKeywords.put( "true", TokenType.TRUE );
unreservedKeywords.put( "false", TokenType.FALSE );
unreservedKeywords.put( "provide", TokenType.PROVIDE );
}
/**
* This class represents an input token read by the Scanner class.
*
* @see Scanner
* @author Fabrizio Montesi
* @version 1.0
*
*/
public static class Token
{
private final TokenType type;
private final String content;
private final boolean isUnreservedKeyword;
/**
* Constructor. The content of the token will be set to "".
* @param type the type of this token
*/
public Token( TokenType type )
{
this.type = type;
this.content = "";
this.isUnreservedKeyword = false;
}
/**
* Constructor.
* @param type the type of this token
* @param content the content of this token
*/
public Token( TokenType type, String content )
{
this.type = type;
this.content = content;
this.isUnreservedKeyword = false;
}
/**
* Constructor.
* @param type the type of this token
* @param content the content of this token
* @param isUnreservedKeyword specifies whether this token is an unreserved keyword
*/
public Token( TokenType type, String content, boolean isUnreservedKeyword )
{
this.type = type;
this.content = content;
this.isUnreservedKeyword = isUnreservedKeyword;
}
/**
* Returns the content of this token.
* @return the content of this token
*/
public String content()
{
return content;
}
/**
* Returns the type of this token.
* @return the type of this token
*/
public TokenType type()
{
return type;
}
/**
* Returns <code>true</code> if this token can be considered as a valid
* value for a constant, <code>false</code> otherwise.
* @return <code>true</code> if this token can be considered as a valid
* value for a constant, <code>false</code> otherwise
*/
public boolean isValidConstant()
{
return type == TokenType.STRING ||
type == TokenType.INT ||
type == TokenType.ID ||
type == TokenType.LONG ||
type == TokenType.TRUE ||
type == TokenType.FALSE ||
type == TokenType.DOUBLE;
}
/**
* Equivalent to <code>is(TokenType.EOF)</code>
* @return <code>true</code> if this token has type <code>TokenType.EOF</code>, false otherwise
*/
public boolean isEOF()
{
return ( type == TokenType.EOF );
}
/**
* Returns <code>true</code> if this token has the passed type, <code>false</code> otherwise.
* @param compareType the type to compare the type of this token with
* @return <code>true</code> if this token has the passed type, <code>false</code> otherwise
*/
public boolean is( TokenType compareType )
{
return ( type == compareType );
}
/**
* Returns <code>true</code> if this token has a different type from the passed one, <code>false</code> otherwise.
* @param compareType the type to compare the type of this token with
* @return <code>true</code> if this token has a different type from the passed one, <code>false</code> otherwise
*/
public boolean isNot( TokenType compareType )
{
return ( type != compareType );
}
/**
* Returns <code>true</code> if this token has type <code>TokenType.ID</code>
* and its content is equal to the passed parameter, <code>false</code> otherwise.
* @param keyword the keyword to check the content of this token against
* @return <code>true</code> if this token has type <code>TokenType.ID</code>
* and its content is equal to the passed parameter, <code>false</code> otherwise
*/
public boolean isKeyword( String keyword )
{
return( type == TokenType.ID && content.equals( keyword ) );
}
/**
* Returns <code>true</code> if this token has type <code>TokenType.ID</code>
* or is a token for an unreserved keyword, <code>false</code> otherwise.
* @return <code>true</code> if this token has type <code>TokenType.ID</code>
* or is a token for an unreserved keyword, <code>false</code> otherwise.
*/
public boolean isIdentifier()
{
return( type == TokenType.ID || isUnreservedKeyword );
}
/**
* This method behaves as {@link #isKeyword(java.lang.String) isKeyword}, except that
* it is case insensitive.
* @param keyword the keyword to check the content of this token against
* @return
*/
public boolean isKeywordIgnoreCase( String keyword )
{
return( type == TokenType.ID && content.equalsIgnoreCase( keyword ) );
}
}
private final InputStream stream; // input stream
private final InputStreamReader reader; // data input
protected char ch; // current character
protected int currInt; // current stream int
protected int state; // current state
private int line; // current line
private final URI source; // source name
/**
* Constructor
* @param stream the <code>InputStream</code> to use for input reading
* @param source the source URI of the stream
* @param charset the character encoding
* @throws java.io.IOException if the input reading initialization fails
*/
public Scanner( InputStream stream, URI source, String charset )
throws IOException
{
this.stream = stream;
this.reader = charset != null ? new InputStreamReader( stream, charset ) : new InputStreamReader( stream );
this.source = source;
line = 1;
readChar();
}
public String readWord()
throws IOException
{
return readWord( true );
}
public String readWord( boolean readChar )
throws IOException
{
StringBuilder buffer = new StringBuilder();
if ( readChar ) {
readChar();
}
do {
buffer.append( ch );
readChar();
} while( !isSeparator( ch ) );
return buffer.toString();
}
private final StringBuilder tokenBuilder = new StringBuilder( 64 );
private void resetTokenBuilder()
{
tokenBuilder.setLength( 0 );
}
public String readLine()
throws IOException
{
resetTokenBuilder();
readChar();
while( !isNewLineChar( ch ) ) {
tokenBuilder.append( ch );
readChar();
}
return tokenBuilder.toString();
}
public static String addStringTerminator( String str )
{
return str + -1;
}
public InputStream inputStream()
{
return stream;
}
/**
* Returns character encoding
* @return character encoding
*/
public String charset()
{
return reader.getEncoding();
}
/**
* Returns the current line the scanner is reading.
*
* @return the current line the scanner is reading.
*/
public int line()
{
return line;
}
/**
* Returns the source URI the scanner is reading.
*
* @return the source URI the scanner is reading
*/
public URI source()
{
return source;
}
public String sourceName()
{
return source.getSchemeSpecificPart();
}
/**
* Eats all separators (whitespace) until the next input.
* @throws IOException
*/
public void eatSeparators()
throws IOException
{
while( isSeparator( ch ) ) {
readChar();
}
}
public void eatSeparatorsUntilEOF()
throws IOException
{
while( isSeparator( ch ) && stream.available() > 0 ) {
readChar();
}
}
/**
* Checks whether a character is a separator (whitespace).
* @param c the character to check as a whitespace
* @return <code>true</code> if <code>c</code> is a separator (whitespace)
*/
public static boolean isSeparator( char c )
{
return isNewLineChar( c ) || c == '\t' || c == ' ';
}
/**
* Checks whether a character is an overflow character.
* @param c the character to check
* @return <code>true</code> if <code>c</code> is an overflow character
*/
private static boolean isOverflowChar( char c )
{
return ( (int) c >= Character.MAX_VALUE );
}
/**
* Checks whether a character is a newline character.
* @param c the character to check
* @return <code>true</code> if <code>c</code> is a newline character
*/
public static boolean isNewLineChar( char c )
{
return ( c == '\n' || c == '\r' );
}
/**
* Reads the next character and loads it into the scanner local state.
* @throws IOException if the source cannot be read
*/
public final void readChar()
throws IOException
{
currInt = reader.read();
ch = (char) currInt;
if ( ch == '\n' ) {
line++;
}
}
/**
* Returns the current character in the scanner local state.
* @return the current character in the scanner local state
*/
public char currentCharacter()
{
return ch;
}
/**
* Consumes characters from the source text and returns its corresponding token.
* @return the token corresponding to the consumed characters
* @throws IOException if not enough characters can be read from the source
*/
public Token getToken()
throws IOException
{
boolean keepRun = true;
state = 1;
while ( currInt != -1 && isSeparator( ch ) ) {
readChar();
}
if ( currInt == -1 ) {
return new Token( TokenType.EOF );
}
boolean stopOneChar = false;
Token retval = null;
resetTokenBuilder();
while ( keepRun ) {
if ( currInt == -1 && retval == null ) {
keepRun = false; // We *need* a token at this point
}
switch( state ) {
/* When considering multi-characters tokens (states > 1),
* remember to read another character in case of a
* specific character (==) check.
*/
case 1: // First character
if ( Character.isLetter( ch ) || ch == '_' ) {
state = 2;
} else if ( Character.isDigit( ch ) ) {
state = 3;
} else if ( ch == '"' ) {
state = 4;
} else if ( ch == '+' ) {
state = 5;
} else if ( ch == '*' ) {
state = 23;
} else if ( ch == '=' ) {
state = 6;
} else if ( ch == '|' ) {
state = 7;
} else if ( ch == '&' ) {
state = 8;
} else if ( ch == '<' ) {
state = 9;
} else if ( ch == '>' ) {
state = 10;
} else if ( ch == '!' ) {
state = 11;
} else if ( ch == '/' ) {
state = 12;
} else if ( ch == '-' ) {
state = 14;
} else if ( ch == '.') { // DOT or REAL
state = 16;
} else { // ONE CHARACTER TOKEN
if ( ch == '(' ) {
retval = new Token( TokenType.LPAREN );
} else if ( ch == ')' ) {
retval = new Token( TokenType.RPAREN );
} else if ( ch == '[' ) {
retval = new Token( TokenType.LSQUARE );
} else if ( ch == ']' ) {
retval = new Token( TokenType.RSQUARE );
} else if ( ch == '{' ) {
retval = new Token( TokenType.LCURLY );
} else if ( ch == '}' ) {
retval = new Token( TokenType.RCURLY );
} else if ( ch == '@' ) {
retval = new Token( TokenType.AT );
} else if ( ch == ':' ) {
retval = new Token( TokenType.COLON );
} else if ( ch == ',' ) {
retval = new Token( TokenType.COMMA );
} else if ( ch == ';' ) {
retval = new Token( TokenType.SEQUENCE );
} else if ( ch == '%' ) {
retval = new Token( TokenType.PERCENT_SIGN );
//else if ( ch == '.' )
//retval = new Token( TokenType.DOT );
} else if ( ch == '
retval = new Token( TokenType.HASH );
} else if ( ch == '^' ) {
retval = new Token( TokenType.CARET );
} else if ( ch == '?' ) {
retval = new Token( TokenType.QUESTION_MARK );
}
/*else if ( ch == '$' )
retval = new Token( TokenType.DOLLAR );*/
readChar();
}
break;
case 2: // ID (or unreserved keyword)
if ( !Character.isLetterOrDigit( ch ) && ch != '_' ) {
String str = tokenBuilder.toString();
TokenType tt = unreservedKeywords.get( str );
if ( tt != null ) {
// It is an unreserved keyword
retval = new Token( tt, str, true );
} else {
// It is a normal ID, not corresponding to any keyword
retval = new Token( TokenType.ID, str );
}
}
break;
case 3: // INT (or LONG, or DOUBLE)
if ( ch == 'e'|| ch == 'E' ){
state = 19;
} else if ( !Character.isDigit( ch ) && ch != '.' ) {
if ( ch == 'l' || ch == 'L' ) {
retval = new Token( TokenType.LONG, tokenBuilder.toString() );
readChar();
} else {
retval = new Token( TokenType.INT, tokenBuilder.toString() );
}
} else if ( ch == '.' ) {
tokenBuilder.append( ch );
readChar();
if ( !Character.isDigit( ch ) ) {
retval = new Token( TokenType.ERROR, tokenBuilder.toString() );
}
else state = 17; // recognized a DOUBLE
}
break;
case 4: // STRING
if ( ch == '"' ) {
retval = new Token( TokenType.STRING, tokenBuilder.toString().substring( 1 ) );
readChar();
} else if ( ch == '\\' ) { // Parse special characters
readChar();
if ( ch == '\\' )
tokenBuilder.append( '\\' );
else if ( ch == 'n' )
tokenBuilder.append( '\n' );
else if ( ch == 't' )
tokenBuilder.append( '\t' );
else if ( ch == 'r' )
tokenBuilder.append( '\r' );
else if ( ch == '"' )
tokenBuilder.append( '"' );
else if ( ch == 'u' )
tokenBuilder.append( 'u' );
else
throw new IOException( "malformed string: bad \\ usage" );
stopOneChar = true;
readChar();
}
break;
case 5: // PLUS OR CHOICE
if ( ch == '=' ) {
retval = new Token( TokenType.ADD_ASSIGN );
readChar();
} else if ( ch == '+' ) {
retval = new Token( TokenType.INCREMENT );
readChar();
} else {
retval = new Token( TokenType.PLUS );
}
break;
case 23: // MULTIPLY or MULTIPLY_ASSIGN
if ( ch == '=' ) {
retval = new Token( TokenType.MULTIPLY_ASSIGN );
readChar();
} else {
retval = new Token( TokenType.ASTERISK, "*" );
}
break;
case 6: // ASSIGN OR EQUAL
if ( ch == '=' ) {
retval = new Token( TokenType.EQUAL );
readChar();
} else if ( ch == '>' ) {
retval = new Token( TokenType.ARROW );
readChar();
} else
retval = new Token( TokenType.ASSIGN );
break;
case 7: // PARALLEL OR LOGICAL OR
if ( ch == '|' ) {
retval = new Token( TokenType.OR );
readChar();
} else
retval = new Token( TokenType.PARALLEL );
break;
case 8: // LOGICAL AND
if ( ch == '&' ) {
retval = new Token( TokenType.AND );
readChar();
}
break;
case 9: // LANGLE OR MINOR_OR_EQUAL OR DEEP_COPY_LEFT
if ( ch == '=' ) {
retval = new Token( TokenType.MINOR_OR_EQUAL );
readChar();
} else if ( ch == '<' ) {
retval = new Token( TokenType.DEEP_COPY_LEFT );
readChar();
} else
retval = new Token( TokenType.LANGLE );
break;
case 10: // RANGLE OR MINOR_OR_EQUAL
if ( ch == '=' ) {
retval = new Token( TokenType.MAJOR_OR_EQUAL );
readChar();
} else
retval = new Token( TokenType.RANGLE );
break;
case 11: // NOT OR NOT_EQUAL
if ( ch == '=' ) {
retval = new Token( TokenType.NOT_EQUAL );
readChar();
} else
retval = new Token( TokenType.NOT );
break;
case 12: // DIVIDE OR BEGIN_COMMENT OR LINE_COMMENT
if ( ch == '*' ) {
state = 13;
} else if ( ch == '/' ) {
state = 15;
} else if( ch == '=' ) {
retval = new Token( TokenType.DIVIDE_ASSIGN );
readChar();
} else
retval = new Token( TokenType.DIVIDE );
break;
case 13: // WAITING FOR END_COMMENT
if ( ch == '*' ) {
readChar();
stopOneChar = true;
if ( ch == '/' ) {
readChar();
retval = getToken();
} else if ( ch == '!' ) {
resetTokenBuilder();
readChar();
state = 21;
}
}
break;
case 14: // MINUS OR (negative) NUMBER OR POINTS_TO
if ( Character.isDigit( ch ) )
state = 3;
else if ( ch == '-' ) {
retval = new Token( TokenType.DECREMENT );
readChar();
} else if ( ch == '>' ) {
retval = new Token( TokenType.POINTS_TO );
readChar();
} else if ( ch == '=' ) {
retval = new Token( TokenType.MINUS_ASSIGN );
readChar();
} else if ( ch == '.' ) {
tokenBuilder.append( ch );
readChar();
if ( !Character.isDigit( ch ) )
retval = new Token( TokenType.ERROR, "-." );
else
state = 17;
} else
retval = new Token( TokenType.MINUS );
break;
case 15: // LINE_COMMENT: waiting for end of line
if ( isNewLineChar( ch ) || isOverflowChar( ch ) ) {
readChar();
retval = getToken();
}
break;
case 16: // DOT
if ( !Character.isDigit( ch ) )
retval = new Token( TokenType.DOT );
else
state = 17; // It's a REAL
break;
case 17: // REAL "."[0-9]+
if ( ch == 'E' || ch == 'e' )
state = 18;
else if ( !Character.isDigit( ch ) )
retval = new Token( TokenType.DOUBLE, tokenBuilder.toString() );
break;
case 18: // Scientific notation, first char after 'E'
if ( ch == '-' || ch == '+' )
state = 19;
else if ( Character.isDigit( ch ) )
state = 20;
else
retval = new Token( TokenType.ERROR );
break;
case 19: // Scientific notation, first exp. digit
if ( !Character.isDigit( ch ) )
retval = new Token( TokenType.ERROR );
else
state = 20;
break;
case 20: // Scientific notation: from second digit to end
if ( !Character.isDigit( ch ) )
retval = new Token( TokenType.DOUBLE, tokenBuilder.toString() );
break;
case 21: // Documentation comment
if ( ch == '*' ) {
readChar();
stopOneChar = true;
if ( ch == '/' ) {
readChar();
retval = new Token( TokenType.DOCUMENTATION_COMMENT, tokenBuilder.toString() );
}
}
break;
default:
retval = new Token( TokenType.ERROR, tokenBuilder.toString() );
break;
}
if ( retval == null ) {
if ( stopOneChar )
stopOneChar = false;
else {
tokenBuilder.append( ch );
readChar();
}
} else {
keepRun = false; // Ok, we are done.
}
}
if ( retval == null ) {
retval = new Token( TokenType.ERROR );
}
return retval;
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public final class MainPanel extends JPanel {
private final JComboBox<String> dirCombo = new JComboBox<>();
private final JFileChooser fileChooser = new JFileChooser();
private final JTextArea textArea = new JTextArea();
private final JProgressBar progress = new JProgressBar();
private final JPanel statusPanel = new JPanel(new BorderLayout());
private final JButton runButton = new JButton("Run");
private final JButton cancelButton = new JButton("Cancel");
private final JButton openButton = new JButton("Choose...");
private transient SwingWorker<String, Message> worker;
private MainPanel() {
super(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement(System.getProperty("user.dir"));
dirCombo.setModel(model);
dirCombo.setFocusable(false);
textArea.setEditable(false);
statusPanel.add(progress);
statusPanel.setVisible(false);
runButton.addActionListener(e -> {
updateComponentStatus(true);
executeWorker();
});
cancelButton.addActionListener(e -> {
if (Objects.nonNull(worker) && !worker.isDone()) {
worker.cancel(true);
}
// worker = null;
});
openButton.addActionListener(e -> {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setSelectedFile(new File(Objects.toString(dirCombo.getEditor().getItem())));
Component c = dirCombo.getRootPane();
int fcSelected = fileChooser.showOpenDialog(c);
if (fcSelected == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Objects.isNull(file) || !file.isDirectory()) {
textArea.setText("Please select directory.");
} else {
String path = file.getAbsolutePath();
textArea.setText(path);
addItem(dirCombo, path, 4);
repaint();
}
} else if (fcSelected == JFileChooser.CANCEL_OPTION) {
textArea.setText("JFileChooser cancelled.");
} else {
UIManager.getLookAndFeel().provideErrorFeedback(c);
textArea.setText("JFileChooser error.");
}
});
JPanel box1 = new JPanel(new BorderLayout(5, 5));
box1.add(new JLabel("Search folder:"), BorderLayout.WEST);
box1.add(dirCombo);
box1.add(openButton, BorderLayout.EAST);
Box box2 = Box.createHorizontalBox();
box2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box2.add(Box.createHorizontalGlue());
box2.add(runButton);
box2.add(Box.createHorizontalStrut(2));
box2.add(cancelButton);
JPanel panel = new JPanel(new BorderLayout());
panel.add(box1, BorderLayout.NORTH);
panel.add(box2, BorderLayout.SOUTH);
add(new JScrollPane(textArea));
add(panel, BorderLayout.NORTH);
add(statusPanel, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public final class FileSearchTask extends RecursiveFileSearchTask {
public FileSearchTask(File dir) {
super(dir);
}
@Override protected void process(List<Message> chunks) {
// System.out.println("process() is EDT?: " + EventQueue.isDispatchThread());
if (isCancelled()) {
return;
}
if (!isDisplayable()) {
// System.out.println("process: DISPOSE_ON_CLOSE");
cancel(true);
return;
}
chunks.forEach(MainPanel.this::updateMessage);
}
@Override protected void done() {
// System.out.println("done() is EDT?: " + EventQueue.isDispatchThread());
if (!isDisplayable()) {
// System.out.println("done: DISPOSE_ON_CLOSE");
cancel(true);
return;
}
updateComponentStatus(false);
String text;
if (isCancelled()) {
text = "Cancelled";
} else {
try {
text = get();
} catch (InterruptedException | ExecutionException ex) {
text = "Interrupted";
Thread.currentThread().interrupt();
}
}
appendLine("
appendLine(text);
}
}
public void updateComponentStatus(boolean start) {
if (start) {
addItem(dirCombo, Objects.toString(dirCombo.getEditor().getItem()), 4);
statusPanel.setVisible(true);
dirCombo.setEnabled(false);
openButton.setEnabled(false);
runButton.setEnabled(false);
cancelButton.setEnabled(true);
progress.setIndeterminate(true);
textArea.setText("");
} else {
dirCombo.setEnabled(true);
openButton.setEnabled(true);
runButton.setEnabled(true);
cancelButton.setEnabled(false);
statusPanel.setVisible(false);
}
}
public static void addItem(JComboBox<String> dirCombo, String str, int max) {
if (Objects.isNull(str) || str.isEmpty()) {
return;
}
dirCombo.setVisible(false);
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) dirCombo.getModel();
model.removeElement(str);
model.insertElementAt(str, 0);
if (model.getSize() > max) {
model.removeElementAt(max);
}
dirCombo.setSelectedIndex(0);
dirCombo.setVisible(true);
}
public void executeWorker() {
File dir = new File(dirCombo.getItemAt(dirCombo.getSelectedIndex()));
worker = new FileSearchTask(dir);
worker.addPropertyChangeListener(new ProgressListener(progress));
worker.execute();
}
public void updateMessage(Message m) {
if (m.append) {
appendLine(m.text);
} else {
textArea.setText(m.text + "\n");
}
}
public void appendLine(String str) {
textArea.append(str + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
// class RecursiveFileSearchTask extends SwingWorker<String, Message> {
// private int counter;
// private final File dir;
// protected RecursiveFileSearchTask(File dir) {
// super();
// this.dir = dir;
// @Override protected String doInBackground() {
// if (Objects.isNull(dir) || !dir.exists()) {
// publish(new Message("The directory does not exist.", true));
// return "Error";
// List<File> list = new ArrayList<>();
// // ArrayList<Path> list = new ArrayList<>();
// try {
// counter = 0;
// recursiveSearch(dir, list);
// } catch (InterruptedException ex) {
// // recursiveSearch(dir.toPath(), list);
// // } catch (Exception ex) {
// publish(new Message("The search was canceled", true));
// return "Interrupted1";
// firePropertyChange("clear-JTextArea", "", "");
// int lengthOfTask = list.size();
// publish(new Message("Length Of Task: " + lengthOfTask, false));
// try {
// int current = 0;
// while (current < lengthOfTask && !isCancelled()) {
// // if (!progress.isDisplayable()) {
// // return "Disposed";
// File file = list.get(current);
// // Path path = list.get(current);
// Thread.sleep(50);
// setProgress(100 * current / lengthOfTask);
// current++;
// publish(new Message(current + "/" + lengthOfTask + ", " + file.getAbsolutePath(), true));
// } catch (InterruptedException ex) {
// return "Interrupted";
// return "Done";
// private void recursiveSearch(File dir, List<File> list) throws InterruptedException {
// // System.out.println("recursiveSearch() is EDT?: " + EventQueue.isDispatchThread());
// for (String name : dir.list()) {
// if (Thread.interrupted()) {
// throw new InterruptedException();
// File dir = new File(dir, name);
// if (dir.isDirectory()) {
// recursiveSearch(dir, list);
// } else {
// counter++;
// if (counter % 100 == 0) {
// publish(new Message("Results:" + counter + "\n", false));
// list.add(dir);
class RecursiveFileSearchTask extends SwingWorker<String, Message> {
protected int counter;
private final File dir;
protected RecursiveFileSearchTask(File dir) {
super();
this.dir = dir;
}
@Override protected String doInBackground() throws InterruptedException {
if (Objects.isNull(dir) || !dir.exists()) {
publish(new Message("The directory does not exist.", true));
return "Error";
}
List<Path> list = new ArrayList<>();
try {
counter = 0;
recursiveSearch(dir.toPath(), list);
} catch (IOException ex) {
publish(new Message("The search was canceled", true));
return "Interrupted1";
}
firePropertyChange("clear-JTextArea", "", "");
int lengthOfTask = list.size();
publish(new Message("Length Of Task: " + lengthOfTask, false));
publish(new Message("
int idx = 0;
while (idx < lengthOfTask && !isCancelled()) {
doSomething(list, idx);
idx++;
}
return "Done";
}
protected void doSomething(List<Path> list, int idx) throws InterruptedException {
int lengthOfTask = list.size();
setProgress(100 * idx / lengthOfTask);
Thread.sleep(10);
Path path = list.get(idx);
int current = idx + 1;
publish(new Message(current + "/" + lengthOfTask + ", " + path, true));
}
private void recursiveSearch(Path dirPath, List<Path> list) throws IOException {
Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Thread.interrupted()) {
throw new IOException();
}
if (attrs.isRegularFile()) {
counter++;
if (counter % 100 == 0) {
publish(new Message("Results:" + counter + "\n", false));
}
list.add(file);
}
return FileVisitResult.CONTINUE;
}
});
}
}
class ProgressListener implements PropertyChangeListener {
private final JProgressBar progressBar;
protected ProgressListener(JProgressBar progressBar) {
this.progressBar = progressBar;
this.progressBar.setValue(0);
}
@Override public void propertyChange(PropertyChangeEvent e) {
String strPropertyName = e.getPropertyName();
if ("progress".equals(strPropertyName)) {
progressBar.setIndeterminate(false);
int progress = (Integer) e.getNewValue();
progressBar.setValue(progress);
}
}
}
class Message {
public final String text;
public final boolean append;
protected Message(String text, boolean append) {
this.text = text;
this.append = append;
}
}
|
package org.eclipse.smarthome.core.thing.internal.console;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.smarthome.core.events.EventPublisher;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ManagedThingProvider;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingRegistry;
import org.eclipse.smarthome.core.thing.ThingStatusInfo;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.events.ThingEventFactory;
import org.eclipse.smarthome.core.thing.i18n.ThingStatusInfoI18nLocalizationService;
import org.eclipse.smarthome.io.console.Console;
import org.eclipse.smarthome.io.console.extensions.AbstractConsoleCommandExtension;
public class ThingConsoleCommandExtension extends AbstractConsoleCommandExtension {
private static final String SUBCMD_LIST = "list";
private static final String SUBCMD_CLEAR = "clear";
private static final String SUBCMD_REMOVE = "remove";
private static final String SUBCMD_TRIGGER = "trigger";
private ManagedThingProvider managedThingProvider;
private ThingRegistry thingRegistry;
private ThingStatusInfoI18nLocalizationService thingStatusInfoI18nLocalizationService;
private EventPublisher eventPublisher;
public ThingConsoleCommandExtension() {
super("things", "Access your thing registry.");
}
@Override
public void execute(String[] args, Console console) {
Collection<Thing> things = thingRegistry.getAll();
if (args.length > 0) {
String subCommand = args[0];
switch (subCommand) {
case SUBCMD_LIST:
printThings(console, things);
return;
case SUBCMD_CLEAR:
removeAllThings(console, things);
return;
case SUBCMD_REMOVE:
if (args.length > 1) {
ThingUID thingUID = new ThingUID(args[1]);
removeThing(console, things, thingUID);
} else {
console.println("Specify thing id to remove: things remove <thingUID> (e.g. \"hue:light:1\")");
}
return;
case SUBCMD_TRIGGER:
if (args.length > 1) {
triggerChannel(console, args[1], args[2]);
} else {
console.println("Command '" + subCommand + "' needs arguments <channelUID> [<event>]");
}
break;
default:
break;
}
} else {
printUsage(console);
}
}
private void triggerChannel(Console console, String channelUid, String event) {
eventPublisher.post(ThingEventFactory.createTriggerEvent(event, new ChannelUID(channelUid)));
}
private void removeThing(Console console, Collection<Thing> things, ThingUID thingUID) {
Thing removedThing = this.managedThingProvider.remove(thingUID);
if (removedThing != null) {
console.println("Thing '" + thingUID + "' successfully removed.");
} else {
console.println("Could not delete thing " + thingUID + ".");
}
}
private void removeAllThings(Console console, Collection<Thing> things) {
int numberOfThings = things.size();
for (Thing thing : things) {
managedThingProvider.remove(thing.getUID());
}
console.println(numberOfThings + " things successfully removed.");
}
@Override
public List<String> getUsages() {
return Arrays.asList(new String[] { buildCommandUsage(SUBCMD_LIST, "lists all things"),
buildCommandUsage(SUBCMD_CLEAR, "removes all managed things"),
buildCommandUsage(SUBCMD_REMOVE + " <thingUID>", "removes a thing"),
buildCommandUsage(SUBCMD_TRIGGER + " <channelUID> [<event>]",
"triggers the <channelUID> with <event> (if given)") });
}
private void printThings(Console console, Collection<Thing> things) {
if (things.isEmpty()) {
console.println("No things found.");
}
for (Thing thing : things) {
String id = thing.getUID().toString();
String thingType = thing instanceof Bridge ? "Bridge" : "Thing";
ThingStatusInfo status = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing, null);
ThingUID bridgeUID = thing.getBridgeUID();
String label = thing.getLabel();
console.println(String.format("%s (Type=%s, Status=%s, Label=%s, Bridge=%s)", id, thingType, status, label,
bridgeUID));
}
}
protected void setManagedThingProvider(ManagedThingProvider managedThingProvider) {
this.managedThingProvider = managedThingProvider;
}
protected void setThingRegistry(ThingRegistry thingRegistry) {
this.thingRegistry = thingRegistry;
}
protected void unsetManagedThingProvider(ManagedThingProvider managedThingProvider) {
this.managedThingProvider = null;
}
protected void unsetThingRegistry(ThingRegistry thingRegistry) {
this.thingRegistry = null;
}
protected void setThingStatusInfoI18nLocalizationService(
ThingStatusInfoI18nLocalizationService thingStatusInfoI18nLocalizationService) {
this.thingStatusInfoI18nLocalizationService = thingStatusInfoI18nLocalizationService;
}
protected void unsetThingStatusInfoI18nLocalizationService(
ThingStatusInfoI18nLocalizationService thingStatusInfoI18nLocalizationService) {
this.thingStatusInfoI18nLocalizationService = null;
}
protected void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
protected void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
}
|
package tools.vitruv.domains.emf.monitorededitor.monitor;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.ecore.change.ChangeDescription;
import org.eclipse.emf.ecore.resource.Resource;
import tools.vitruv.domains.emf.monitorededitor.IEditorPartAdapterFactory.IEditorPartAdapter;
import tools.vitruv.domains.emf.monitorededitor.tools.ISaveEventListener;
import tools.vitruv.domains.emf.monitorededitor.tools.ResourceReloadListener;
import tools.vitruv.domains.emf.monitorededitor.tools.SaveEventListenerMgr;
import tools.vitruv.framework.change.description.TransactionalChange;
import tools.vitruv.framework.change.recording.ChangeRecorder;
import tools.vitruv.framework.uuid.UuidGeneratorAndResolver;
import tools.vitruv.framework.uuid.UuidGeneratorAndResolverImpl;
import tools.vitruv.framework.vsum.VirtualModel;
/**
* <p>
* A listener for EMF/GMF editors recording the changes in the editor's EMF model, calling the
* method <code>onSavedResource()</code> whenever the user saves the edited file.
* </p>
*
* <p>
* The listener is initially inactive and can be activated by calling <code>initialize()</code>. It
* remains active until <code>dispose()</code> is called.
* </p>
*
* <p>
* This listener class can be used by extending it and implementing the
* <code>onSavedResource()</code> method.
* </p>
*/
public abstract class EMFModelChangeRecordingEditorSaveListener {
/** The logger for {@link EMFModelChangeRecordingEditorSaveListener} instances. */
private static final Logger LOGGER = Logger.getLogger(EMFModelChangeRecordingEditorSaveListener.class);
/**
* <code>true</code> iff the listener has been initialized and is operational.
*/
private boolean isInitialized = false;
/**
* The {@link ChangeRecorder} used to record changes to the edited model.
*/
private ChangeRecorder changeRecorder;
/** The monitored EMF model resource. */
private final Resource targetResource;
/** The listener getting fired when the user saves the edited file. */
private final SaveEventListenerMgr saveActionListenerManager;
private VirtualModel virtualModel;
/**
* A constructor for {@link EMFModelChangeRecordingEditorSaveListener} instances. The listener
* remains inactive until <code>initialize()</code> is called.
*
* @param editorAdapter
* An {@link IEditorPartAdapter} instance adapting the EMF/GMF editor which needs to be
* monitored.
*/
public EMFModelChangeRecordingEditorSaveListener(IEditorPartAdapter editorAdapter) {
this.targetResource = editorAdapter.getEditedModelResource();
this.saveActionListenerManager = new SaveEventListenerMgr();
saveActionListenerManager.restrictSaveActionsToEditorPart(editorAdapter.getEditorPart());
LOGGER.trace("Constructed a listener for an editor of type " + editorAdapter.getClass().getCanonicalName()
+ " for Res. " + targetResource);
}
/**
* @return <code>true</code> iff the listener has been initialized.
*/
public boolean isInitialized() {
return isInitialized;
}
/**
* Creates a {@link ISaveEventListener} instance reading out the <code>changeRecorder</code> and
* calling <code>onSavedResource()</code> after the user has saved the edited file.
*
* @return The newly created {@link SaveActionExecutionListener}.
*/
protected ISaveEventListener createSaveActionExecutionListener() {
return new ISaveEventListener() {
@Override
public void onPreSave() {
}
@Override
public void onPostSave() {
var changes = readOutChangesAndEndRecording();
LOGGER.trace("Detected a user save action, got change descriptions: " + changes);
onSavedResource(changes);
resetChangeRecorder();
}
@Override
public void postExecuteFailure(String commandId, ExecutionException exception) {
}
};
}
private void installResourceReloadListener() {
ResourceReloadListener rrl = new ResourceReloadListener(targetResource) {
@Override
protected void onResourceUnloaded() {
LOGGER.trace("Detected a resource unload event, deactivating the change recorder.");
deactivateChangeRecorder();
}
@Override
protected void onResourceLoaded() {
LOGGER.trace("Detected a resource load event, resetting the change recorder.");
resetChangeRecorder();
}
};
targetResource.eAdapters().add(rrl);
}
private void deactivateChangeRecorder() {
if (changeRecorder != null) {
changeRecorder.close();
}
changeRecorder = null;
}
/**
* Resets the change recorder by replacing it with a new one.
*/
protected void resetChangeRecorder() {
deactivateChangeRecorder();
UuidGeneratorAndResolver globalUuidGeneratorAndResolver = virtualModel != null
? virtualModel.getUuidGeneratorAndResolver()
: null;
// TODO Set strict mode to false
UuidGeneratorAndResolver localUuidResolver = new UuidGeneratorAndResolverImpl(globalUuidGeneratorAndResolver,
targetResource.getResourceSet(), false);
changeRecorder = new ChangeRecorder(localUuidResolver);
changeRecorder.addToRecording(targetResource);
changeRecorder.beginRecording();
}
/**
* @return The changes recorded since last resetting the change recorder.
*/
protected List<? extends TransactionalChange> readOutChangesAndEndRecording() {
changeRecorder.endRecording();
return changeRecorder.getChanges();
}
/**
* Initializes the listener. After calling this method, the listener is active until
* <code>dispose()</code> is called.
*/
public void initialize(VirtualModel virtualModel) {
this.virtualModel = virtualModel;
if (!isInitialized) {
resetChangeRecorder();
installResourceReloadListener();
saveActionListenerManager.install(createSaveActionExecutionListener());
isInitialized = true;
} else {
LOGGER.warn("Called initialize() for an initialized instance," + " ignoring the call");
}
}
/**
* Disposes the listener. After calling this method, the listener is inactive until
* <code>initialize()</code> is called.
*/
public void dispose() {
if (isInitialized) {
saveActionListenerManager.dispose();
if (changeRecorder != null) {
changeRecorder.close();
}
isInitialized = false;
} else {
LOGGER.warn("Called dispose() for an uninitialized instance," + " ignoring the call");
}
}
/**
* @return The monitored EMF resource.
*/
public Resource getMonitoredResource() {
return targetResource;
}
/**
* The "listener" method getting called when the user saves the edited file.
*
* @param changeDescription
* The EMF {@link ChangeDescription} describing the changes to the EMF model since last
* saving it (rsp. since opening it, in case it has not been saved yet). This object is
* provided "as is" from a {@link ChangeRecorder} instance.
*/
protected abstract void onSavedResource(List<? extends TransactionalChange> changeDescription);
}
|
package com.sun.xml.xsom.impl.parser;
import com.sun.tools.rngdatatype.ValidationContext;
import com.sun.xml.xsom.XSDeclaration;
import com.sun.xml.xsom.XSSimpleType;
import com.sun.xml.xsom.XmlString;
import com.sun.xml.xsom.impl.Const;
import com.sun.xml.xsom.impl.ForeignAttributesImpl;
import com.sun.xml.xsom.impl.SchemaImpl;
import com.sun.xml.xsom.impl.UName;
import com.sun.xml.xsom.impl.parser.state.NGCCRuntime;
import com.sun.xml.xsom.impl.parser.state.Schema;
import com.sun.xml.xsom.parser.AnnotationParser;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.LocatorImpl;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Stack;
import java.util.regex.Pattern;
/**
* NGCCRuntime extended with various utility methods for
* parsing XML Schema.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class NGCCRuntimeEx extends NGCCRuntime implements PatcherManager {
/** coordinator. */
public final ParserContext parser;
/** The schema currently being parsed. */
public SchemaImpl currentSchema;
/** The @finalDefault value of the current schema. */
public int finalDefault = 0;
/** The @blockDefault value of the current schema. */
public int blockDefault = 0;
/**
* The @elementFormDefault value of the current schema.
* True if local elements are qualified by default.
*/
public boolean elementFormDefault = false;
/**
* The @attributeFormDefault value of the current schema.
* True if local attributes are qualified by default.
*/
public boolean attributeFormDefault = false;
/**
* True if the current schema is in a chameleon mode.
* This changes the way QNames are interpreted.
*
* Life is very miserable with XML Schema, as you see.
*/
public boolean chameleonMode = false;
/**
* URI that identifies the schema document.
* Maybe null if the system ID is not available.
*/
private String documentSystemId;
/**
* Keep the local name of elements encountered so far.
* This information is passed to AnnotationParser as
* context information
*/
private final Stack<String> elementNames = new Stack<>();
/**
* Points to the schema document (the parser of it) that included/imported
* this schema.
*/
private final NGCCRuntimeEx referer;
/**
* Points to the {@link SchemaDocumentImpl} that represents the
* schema document being parsed.
*/
public SchemaDocumentImpl document;
NGCCRuntimeEx( ParserContext _parser ) {
this(_parser,false,null);
}
private NGCCRuntimeEx( ParserContext _parser, boolean chameleonMode, NGCCRuntimeEx referer ) {
this.parser = _parser;
this.chameleonMode = chameleonMode;
this.referer = referer;
// set up the default namespace binding
currentContext = new Context("","",null);
currentContext = new Context("xml","http:
}
public void checkDoubleDefError( XSDeclaration c ) throws SAXException {
if(c==null || ignorableDuplicateComponent(c)) return;
reportError( Messages.format(Messages.ERR_DOUBLE_DEFINITION,c.getName()) );
reportError( Messages.format(Messages.ERR_DOUBLE_DEFINITION_ORIGINAL), c.getLocator() );
}
public static boolean ignorableDuplicateComponent(XSDeclaration c) {
if(Const.schemaNamespace.equals(c.getTargetNamespace())) {
if(c instanceof XSSimpleType) {
// hide artificial "double definitions" on simple types
return true;
}
return c.isGlobal() && "anyType".equals(c.getName()); // ditto for anyType
}
return false;
}
/* registers a patcher that will run after all the parsing has finished. */
@Override
public void addPatcher( Patch patcher ) {
parser.patcherManager.addPatcher(patcher);
}
@Override
public void addErrorChecker( Patch patcher ) {
parser.patcherManager.addErrorChecker(patcher);
}
@Override
public void reportError( String msg, Locator loc ) throws SAXException {
parser.patcherManager.reportError(msg,loc);
}
public void reportError( String msg ) throws SAXException {
reportError(msg,getLocator());
}
/**
* Resolves relative URI found in the document.
*
* @param namespaceURI
* passed to the entity resolver.
* @param relativeUri
* value of the schemaLocation attribute. Can be null.
*
* @return
* non-null if {@link EntityResolver} returned an {@link InputSource},
* or if the relativeUri parameter seems to be pointing to something.
* Otherwise it returns null, in which case import/include should be abandoned.
*/
private InputSource resolveRelativeURL( String namespaceURI, String relativeUri ) throws SAXException {
try {
String baseUri = getLocator().getSystemId();
if(baseUri==null)
// if the base URI is not available, the document system ID is
// better than nothing.
baseUri=documentSystemId;
EntityResolver er = parser.getEntityResolver();
String systemId = null;
if (relativeUri!=null) {
if (isAbsolute(relativeUri)) {
systemId = relativeUri;
} else if (baseUri == null || !isAbsolute(baseUri)) {
throw new IOException("Unable to resolve relative URI " + relativeUri + " because base URI is not absolute: " + baseUri);
} else {
systemId = new URL(new URL(baseUri), relativeUri).toString();
}
}
if (er!=null) {
InputSource is = er.resolveEntity(namespaceURI,systemId == null ? "" : systemId);
if (is == null) {
try {
String normalizedSystemId = URI.create(systemId).normalize().toASCIIString();
is = er.resolveEntity(namespaceURI,normalizedSystemId);
} catch (Exception e) {
// just ignore, this is a second try, return the fallback if this breaks
}
}
if (is != null) {
return is;
}
}
if (systemId!=null)
return new InputSource(systemId);
else
return null;
} catch (IOException e) {
SAXParseException se = new SAXParseException(e.getMessage(),getLocator(),e);
parser.errorHandler.error(se);
return null;
}
}
private static final Pattern P = Pattern.compile(".*[/
private static boolean isAbsolute(String uri) {
int i = uri.indexOf(':');
if (i < 0) {
return false;
}
return !P.matcher(uri.substring(0, i)).matches();
}
/**
* Includes the specified schema.
* */
public void includeSchema( String schemaLocation ) throws SAXException {
NGCCRuntimeEx runtime = new NGCCRuntimeEx(parser,chameleonMode,this);
runtime.currentSchema = this.currentSchema;
runtime.blockDefault = this.blockDefault;
runtime.finalDefault = this.finalDefault;
if( schemaLocation==null ) {
SAXParseException e = new SAXParseException(
Messages.format( Messages.ERR_MISSING_SCHEMALOCATION ), getLocator() );
parser.errorHandler.fatalError(e);
throw e;
}
runtime.parseEntity( resolveRelativeURL(null,schemaLocation),
true, currentSchema.getTargetNamespace(), getLocator() );
}
/**
* Imports the specified schema.
* */
public void importSchema( String ns, String schemaLocation ) throws SAXException {
NGCCRuntimeEx newRuntime = new NGCCRuntimeEx(parser,false,this);
InputSource source = resolveRelativeURL(ns,schemaLocation);
if(source!=null)
newRuntime.parseEntity( source, false, ns, getLocator() );
// if source == null,
// we can't locate this document. Let's just hope that
// we already have the schema components for this schema
// or we will receive them in the future.
}
/**
* Called when a new document is being parsed and checks
* if the document has already been parsed before.
*
* <p>
* Used to avoid recursive inclusion. Note that the same
* document will be parsed multiple times if they are for different
* target namespaces.
*
* <p><strong>Document Graph Model</strong></p>
* <p>
* The challenge we are facing here is that you have a graph of
* documents that reference each other. Each document has an unique
* URI to identify themselves, and references are done by using those.
* The graph may contain cycles.
*
* <p>
* Our goal here is to parse all the documents in the graph, without
* parsing the same document twice. This method implements this check.
*
* <p>
* One complication is the chameleon schema; a document can be parsed
* multiple times if they are under different target namespaces.
*
* <p>
* Also, note that when you resolve relative URIs in the @schemaLocation,
* their base URI is *NOT* the URI of the document.
*
* @return true if the document has already been processed and thus
* needs to be skipped.
*/
public boolean hasAlreadyBeenRead() {
if( documentSystemId!=null ) {
if( documentSystemId.startsWith("file:
// change file:///abc to file:/abc
// JDK File.toURL method produces the latter, but according to RFC
// I don't think that's a valid URL. Since two different ways of
// producing URLs could produce those two different forms,
// we need to canonicalize one to the other.
documentSystemId = "file:/"+documentSystemId.substring(8);
} else {
// if the system Id is not provided, we can't test the identity,
// so we have no choice but to read it.
// the newly created SchemaDocumentImpl will be unique one
}
assert document ==null;
document = new SchemaDocumentImpl( currentSchema, documentSystemId );
SchemaDocumentImpl existing = parser.parsedDocuments.get(document);
if(existing==null) {
parser.parsedDocuments.put(document,document);
} else {
document = existing;
}
assert document !=null;
if(referer!=null) {
assert referer.document !=null : "referer "+referer.documentSystemId+" has docIdentity==null";
referer.document.references.add(this.document);
this.document.referers.add(referer.document);
}
return existing!=null;
}
/**
* Parses the specified entity.
*
* @param importLocation
* The source location of the import/include statement.
* Used for reporting errors.
*/
public void parseEntity( InputSource source, boolean includeMode, String expectedNamespace, Locator importLocation )
throws SAXException {
documentSystemId = source.getSystemId();
try {
Schema s = new Schema(this,includeMode,expectedNamespace);
setRootHandler(s);
try {
parser.parser.parse(source,this, getErrorHandler(), parser.getEntityResolver());
} catch( IOException fnfe ) {
SAXParseException se = new SAXParseException(fnfe.toString(), importLocation, fnfe);
parser.errorHandler.warning(se);
}
} catch( SAXException e ) {
parser.setErrorFlag();
throw e;
}
}
/**
* Creates a new instance of annotation parser.
*
* @return Annotation parser
*/
public AnnotationParser createAnnotationParser() {
if(parser.getAnnotationParserFactory()==null)
return DefaultAnnotationParser.theInstance;
else
return parser.getAnnotationParserFactory().create();
}
/**
* Gets the element name that contains the annotation element.This method works correctly only when called by the annotation handler.
*
* @return Element name
*/
public String getAnnotationContextElementName() {
return elementNames.get( elementNames.size()-2 );
}
/**
* Creates a copy of the current locator object.
*
* @return Locator copy
*/
public Locator copyLocator() {
return new LocatorImpl(getLocator());
}
public ErrorHandler getErrorHandler() {
return parser.errorHandler;
}
@Override
public void onEnterElementConsumed(String uri, String localName, String qname, Attributes atts)
throws SAXException {
super.onEnterElementConsumed(uri, localName, qname, atts);
elementNames.push(localName);
}
@Override
public void onLeaveElementConsumed(String uri, String localName, String qname) throws SAXException {
super.onLeaveElementConsumed(uri, localName, qname);
elementNames.pop();
}
// ValidationContext implementation
// this object lives longer than the parser itself,
// so it's important for this object not to have any reference
// to the parser.
private static class Context implements ValidationContext {
Context( String _prefix, String _uri, Context _context ) {
this.previous = _context;
this.prefix = _prefix;
this.uri = _uri;
}
@Override
public String resolveNamespacePrefix(String p) {
if(p.equals(prefix)) return uri;
if(previous==null) return null;
else return previous.resolveNamespacePrefix(p);
}
private final String prefix;
private final String uri;
private final Context previous;
// XSDLib don't use those methods, so we cut a corner here.
@Override
public String getBaseUri() { return null; }
@Override
public boolean isNotation(String arg0) { return false; }
@Override
public boolean isUnparsedEntity(String arg0) { return false; }
}
private Context currentContext=null;
/** Returns an immutable snapshot of the current context.
*
* @return Snapshot of current context
*/
public ValidationContext createValidationContext() {
return currentContext;
}
public XmlString createXmlString(String value) {
if(value==null) return null;
else return new XmlString(value,createValidationContext());
}
@Override
public void startPrefixMapping( String prefix, String uri ) throws SAXException {
super.startPrefixMapping(prefix,uri);
currentContext = new Context(prefix,uri,currentContext);
}
@Override
public void endPrefixMapping( String prefix ) throws SAXException {
super.endPrefixMapping(prefix);
currentContext = currentContext.previous;
}
// Utility functions
/**
* Parses UName under the given context.
* @param qname Attribute name.
* @return New {@link UName} instance based on attribute name.
*/
public UName parseUName(final String qname ) throws SAXException {
int idx = qname.indexOf(':');
if(idx<0) {
String uri = resolveNamespacePrefix("");
// chamelon behavior. ugly...
if( uri.equals("") && chameleonMode )
uri = currentSchema.getTargetNamespace();
// this is guaranteed to resolve
return new UName(uri,qname,qname);
} else {
String prefix = qname.substring(0,idx);
String uri = currentContext.resolveNamespacePrefix(prefix);
if(uri==null) {
// prefix failed to resolve.
reportError(Messages.format(
Messages.ERR_UNDEFINED_PREFIX,prefix));
uri="undefined"; // replace with a dummy
}
return new UName( uri, qname.substring(idx+1), qname );
}
}
/**
* Utility function for collapsing the namespaces inside qname declarations
* and 'name' attribute values that should contain the qname values
*
* @param text String where whitespaces should be collapsed
* @return String with whitespaces collapsed
*/
public String collapse(String text) {
return collapse((CharSequence) text).toString();
}
/**
* returns true if the specified char is a white space character.
*/
private boolean isWhiteSpace(char ch) {
// most of the characters are non-control characters.
// so check that first to quickly return false for most of the cases.
if (ch > 0x20) {
return false;
}
// other than we have to do four comparisons.
return ch == 0x9 || ch == 0xA || ch == 0xD || ch == 0x20;
}
/**
* This is usually the biggest processing bottleneck.
*
*/
private CharSequence collapse(CharSequence text) {
int len = text.length();
// most of the texts are already in the collapsed form.
// so look for the first whitespace in the hope that we will
// never see it.
int s = 0;
while (s < len) {
if (isWhiteSpace(text.charAt(s))) {
break;
}
s++;
}
if (s == len) // the input happens to be already collapsed.
{
return text;
}
// we now know that the input contains spaces.
// let's sit down and do the collapsing normally.
StringBuilder result = new StringBuilder(len /*allocate enough size to avoid re-allocation*/);
if (s != 0) {
for (int i = 0; i < s; i++) {
result.append(text.charAt(i));
}
result.append(' ');
}
boolean inStripMode = true;
for (int i = s + 1; i < len; i++) {
char ch = text.charAt(i);
boolean b = isWhiteSpace(ch);
if (inStripMode && b) {
continue; // skip this character
}
inStripMode = b;
if (inStripMode) {
result.append(' ');
} else {
result.append(ch);
}
}
// remove trailing whitespaces
len = result.length();
if (len > 0 && result.charAt(len - 1) == ' ') {
result.setLength(len - 1);
}
// whitespaces are already collapsed,
// so all we have to do is to remove the last one character
// if it's a whitespace.
return result;
}
public boolean parseBoolean(String v) {
if(v==null) return false;
v=v.trim();
return v.equals("true") || v.equals("1");
}
@Override
protected void unexpectedX(String token) throws SAXException {
SAXParseException e = new SAXParseException(MessageFormat.format(
"Unexpected {0} appears at line {1} column {2}",
token,
getLocator().getLineNumber(),
getLocator().getColumnNumber()),
getLocator());
parser.errorHandler.fatalError(e);
throw e; // we will abort anyway
}
public ForeignAttributesImpl parseForeignAttributes( ForeignAttributesImpl next ) {
ForeignAttributesImpl impl = new ForeignAttributesImpl(createValidationContext(),copyLocator(),next);
Attributes atts = getCurrentAttributes();
for( int i=0; i<atts.getLength(); i++ ) {
if(atts.getURI(i).length()>0) {
impl.addAttribute(
atts.getURI(i),
atts.getLocalName(i),
atts.getQName(i),
atts.getType(i),
atts.getValue(i)
);
}
}
return impl;
}
}
|
package org.eclipse.smarthome.binding.tradfri.handler;
import static org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants;
import org.eclipse.smarthome.binding.tradfri.internal.CoapCallback;
import org.eclipse.smarthome.binding.tradfri.internal.DeviceUpdateListener;
import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapClient;
import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapEndpoint;
import org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapHandler;
import org.eclipse.smarthome.binding.tradfri.internal.config.TradfriGatewayConfig;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.thing.binding.ThingHandler;
import org.eclipse.smarthome.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
/**
* The {@link TradfriGatewayHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Kai Kreuzer - Initial contribution
*/
public class TradfriGatewayHandler extends BaseBridgeHandler implements CoapCallback {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final String MIN_SUPPORTED_VERSION = "1.2.42";
private TradfriCoapClient deviceClient;
private String gatewayURI;
private String gatewayInfoURI;
private DTLSConnector dtlsConnector;
private CoapEndpoint endPoint;
private final Set<DeviceUpdateListener> deviceUpdateListeners = new CopyOnWriteArraySet<>();
private ScheduledFuture<?> scanJob;
public TradfriGatewayHandler(@NonNull Bridge bridge) {
super(bridge);
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
// there are no channels on the gateway yet
}
@Override
public void initialize() {
TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
if (isNullOrEmpty(configuration.host)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Host must be specified in the configuration!");
return;
}
if (isNullOrEmpty(configuration.code)) {
if (isNullOrEmpty(configuration.identity) || isNullOrEmpty(configuration.preSharedKey)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Either security code or identity and pre-shared key must be provided in the configuration!");
return;
} else {
establishConnection();
}
} else {
if (isOldFirmware()) {
/*
* older firmware - fall back to authentication with security code
* in this case the Thing configuration will not be persisted
*/
logger.warn("Gateway with old firmware - please consider upgrading to the latest version.");
Configuration editedConfig = editConfiguration();
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, "");
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, configuration.code);
updateConfiguration(editedConfig);
establishConnection();
} else {
// Running async operation to retrieve new <'identity','key'> pair
scheduler.execute(() -> {
boolean success = obtainIdentityAndPreSharedKey();
if (success) {
establishConnection();
}
});
}
}
}
private void establishConnection() {
TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/"
+ GATEWAY_DETAILS;
try {
URI uri = new URI(gatewayURI);
deviceClient = new TradfriCoapClient(uri);
} catch (URISyntaxException e) {
logger.error("Illegal gateway URI '{}': {}", gatewayURI, e.getMessage());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
return;
}
DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
builder.setPskStore(new StaticPskStore(configuration.identity, configuration.preSharedKey.getBytes()));
dtlsConnector = new DTLSConnector(builder.build());
endPoint = new TradfriCoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
deviceClient.setEndpoint(endPoint);
updateStatus(ThingStatus.UNKNOWN);
// schedule a new scan every minute
scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
}
/**
* Authenticates against the gateway with the security code in order to receive a pre-shared key for a newly
* generated identity.
* As this requires a remote request, this method might be long-running.
*
* @return true, if credentials were successfully obtained, false otherwise
*/
protected boolean obtainIdentityAndPreSharedKey() {
TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
String identity = UUID.randomUUID().toString().replace("-", "");
String preSharedKey = null;
CoapResponse gatewayResponse;
String authUrl = null;
String responseText = null;
try {
DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
CoapEndpoint authEndpoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
authUrl = "coaps://" + configuration.host + ":" + configuration.port + "/15011/9063";
CoapClient deviceClient = new CoapClient(new URI(authUrl));
deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
deviceClient.setEndpoint(authEndpoint);
JsonObject json = new JsonObject();
json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
gatewayResponse = deviceClient.post(json.toString(), 0);
authEndpoint.destroy();
deviceClient.shutdown();
if (gatewayResponse == null) {
// seems we ran in a timeout, which potentially also happens
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"No response from gateway. Might be due to an invalid security code.");
return false;
}
if (gatewayResponse.isSuccess()) {
responseText = gatewayResponse.getResponseText();
json = new JsonParser().parse(responseText).getAsJsonObject();
preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
if (isNullOrEmpty(preSharedKey)) {
logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(),
configuration.host);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Pre-shared key was not obtain successfully");
return false;
} else {
logger.info("Received pre-shared key for gateway '{}'", configuration.host);
logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
Configuration editedConfig = editConfiguration();
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_CODE, null);
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, identity);
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, preSharedKey);
updateConfiguration(editedConfig);
return true;
}
} else {
logger.warn(
"Failed obtaining pre-shared key for identity '{}' (response code '{}', response text '{}')",
identity, gatewayResponse.getCode(),
isNullOrEmpty(gatewayResponse.getResponseText()) ? "<empty>"
: gatewayResponse.getResponseText());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String
.format("Failed obtaining pre-shared key with status code '%s'", gatewayResponse.getCode()));
}
} catch (URISyntaxException e) {
logger.error("Illegal gateway URI '{}'", authUrl, e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
} catch (JsonParseException e) {
logger.warn("Invalid response recieved from gateway '{}'", responseText, e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
String.format("Invalid response recieved from gateway '%s'", responseText));
}
return false;
}
@Override
public void dispose() {
if (scanJob != null) {
scanJob.cancel(true);
scanJob = null;
}
if (deviceClient != null) {
deviceClient.shutdown();
deviceClient = null;
}
if (endPoint != null) {
endPoint.destroy();
endPoint = null;
}
super.dispose();
}
/**
* Does a request to the gateway to list all available devices/services.
* The response is received and processed by the method {@link onUpdate(JsonElement data)}.
*/
public void startScan() {
if (endPoint != null) {
requestGatewayInfo();
deviceClient.get(new TradfriCoapHandler(this));
}
}
/**
* Returns the root URI of the gateway.
*
* @return root URI of the gateway with coaps scheme
*/
public String getGatewayURI() {
return gatewayURI;
}
/**
* Returns the coap endpoint that can be used within coap clients.
*
* @return the coap endpoint
*/
public CoapEndpoint getEndpoint() {
return endPoint;
}
@Override
public void onUpdate(JsonElement data) {
logger.debug("onUpdate response: {}", data);
if (endPoint != null) {
try {
JsonArray array = data.getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
requestDeviceDetails(array.get(i).getAsString());
}
} catch (JsonSyntaxException e) {
logger.debug("JSON error: {}", e.getMessage());
setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
}
}
}
private synchronized void requestGatewayInfo() {
// we are reusing our coap client and merely temporarily set a gateway info to call
deviceClient.setURI(this.gatewayInfoURI);
deviceClient.asyncGet().thenAccept(data -> {
JsonObject json = new JsonParser().parse(data).getAsJsonObject();
String firmwareVersion = json.get(VERSION).getAsString();
getThing().setProperty(Thing.PROPERTY_FIRMWARE_VERSION, firmwareVersion);
});
// restore root URI
deviceClient.setURI(gatewayURI);
}
private synchronized void requestDeviceDetails(String instanceId) {
// we are reusing our coap client and merely temporarily set a sub-URI to call
deviceClient.setURI(gatewayURI + "/" + instanceId);
deviceClient.asyncGet().thenAccept(data -> {
logger.debug("requestDeviceDetails response: {}", data);
JsonObject json = new JsonParser().parse(data).getAsJsonObject();
deviceUpdateListeners.forEach(listener -> listener.onUpdate(instanceId, json));
});
// restore root URI
deviceClient.setURI(gatewayURI);
}
@Override
public void setStatus(ThingStatus status, ThingStatusDetail statusDetail) {
// are we still connected at all?
if (endPoint != null) {
updateStatus(status, statusDetail);
if (dtlsConnector != null && status == ThingStatus.OFFLINE) {
try {
dtlsConnector.stop();
dtlsConnector.start();
} catch (IOException e) {
logger.debug("Error restarting the DTLS connector: {}", e.getMessage());
}
}
}
}
/**
* Registers a listener, which is informed about device details.
*
* @param listener the listener to register
*/
public void registerDeviceUpdateListener(DeviceUpdateListener listener) {
this.deviceUpdateListeners.add(listener);
}
/**
* Unregisters a given listener.
*
* @param listener the listener to unregister
*/
public void unregisterDeviceUpdateListener(DeviceUpdateListener listener) {
this.deviceUpdateListeners.remove(listener);
}
private boolean isNullOrEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Checks current firmware in the thing properties and compares it with the value of {@link #MIN_SUPPORTED_VERSION}
*
* @return true if current firmware is older than {@value #MIN_SUPPORTED_VERSION}
*/
private boolean isOldFirmware() {
String currentFirmware = thing.getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION);
return currentFirmware == null || MIN_SUPPORTED_VERSION.compareTo(currentFirmware) > 0;
}
@Override
public void thingUpdated(Thing thing) {
super.thingUpdated(thing);
logger.info("Bridge configuration updated. Updating paired things (if any).");
for (Thing t : getThing().getThings()) {
final ThingHandler thingHandler = t.getHandler();
if (thingHandler != null) {
thingHandler.thingUpdated(t);
}
}
}
}
|
package me.xdrop.jrand.generators.time;
import me.xdrop.jrand.Generator;
import me.xdrop.jrand.annotation.Facade;
import me.xdrop.jrand.annotation.PropertyFlag;
import me.xdrop.jrand.generators.basics.NaturalGenerator;
@Facade(accessor = "hour")
public class HourGenerator extends Generator<String> {
private NaturalGenerator nat;
@PropertyFlag("Enable to return an hour between 1 and 24")
private boolean twentyfour;
public HourGenerator() {
this.nat = new NaturalGenerator();
this.nat.min(1).max(12);
}
public int genInt() {
if (twentyfour) {
nat.range(1, 24);
} else {
nat.range(1, 12);
}
return nat.gen();
}
@Override
public String gen() {
return genInt() + "";
}
}
|
package org.jboss.resteasy.reactive.server.core;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.regex.Matcher;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.WriterInterceptor;
import org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext;
import org.jboss.resteasy.reactive.common.util.Encode;
import org.jboss.resteasy.reactive.common.util.PathSegmentImpl;
import org.jboss.resteasy.reactive.server.core.multipart.FormData;
import org.jboss.resteasy.reactive.server.core.serialization.EntityWriter;
import org.jboss.resteasy.reactive.server.injection.ResteasyReactiveInjectionContext;
import org.jboss.resteasy.reactive.server.jaxrs.AsyncResponseImpl;
import org.jboss.resteasy.reactive.server.jaxrs.ContainerRequestContextImpl;
import org.jboss.resteasy.reactive.server.jaxrs.ContainerResponseContextImpl;
import org.jboss.resteasy.reactive.server.jaxrs.HttpHeadersImpl;
import org.jboss.resteasy.reactive.server.jaxrs.ProvidersImpl;
import org.jboss.resteasy.reactive.server.jaxrs.RequestImpl;
import org.jboss.resteasy.reactive.server.jaxrs.SseEventSinkImpl;
import org.jboss.resteasy.reactive.server.jaxrs.UriInfoImpl;
import org.jboss.resteasy.reactive.server.mapping.RuntimeResource;
import org.jboss.resteasy.reactive.server.mapping.URITemplate;
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
import org.jboss.resteasy.reactive.server.spi.ServerHttpRequest;
import org.jboss.resteasy.reactive.server.spi.ServerHttpResponse;
import org.jboss.resteasy.reactive.server.spi.ServerRequestContext;
import org.jboss.resteasy.reactive.server.spi.ServerRestHandler;
import org.jboss.resteasy.reactive.spi.ThreadSetupAction;
public abstract class ResteasyReactiveRequestContext
extends AbstractResteasyReactiveContext<ResteasyReactiveRequestContext, ServerRestHandler>
implements Closeable, ResteasyReactiveInjectionContext, ServerRequestContext {
public static final Object[] EMPTY_ARRAY = new Object[0];
protected final Deployment deployment;
protected final ProvidersImpl providers;
/**
* The parameters array, populated by handlers
*/
private Object[] parameters;
private RuntimeResource target;
/**
* info about path params and other data about previously matched sub resource locators
*/
private PreviousResource previousResource;
/**
* The parameter values extracted from the path.
* <p>
* This is not a map, for two reasons. One is raw performance, as an array causes
* less allocations and is generally faster. The other is that it is possible
* that you can have equivalent templates with different names. This allows the
* mapper to ignore the names, as everything is resolved in terms of indexes.
* <p>
* If there is only a single path param then it is stored directly into the field,
* while multiple params this will be an array. This optimisation allows us to avoid
* allocating anything in the common case that there is zero or one path param.
* <p>
* Note: those are decoded.
*/
private Object pathParamValues;
private UriInfo uriInfo;
/**
* The endpoint to invoke
*/
private Object endpointInstance;
/**
* The result of the invocation
*/
private Object result;
/**
* The supplier of the actual response
*/
private LazyResponse response;
private HttpHeadersImpl httpHeaders;
private Object requestEntity;
private Request request;
private EntityWriter entityWriter;
private ContainerRequestContextImpl containerRequestContext;
private ContainerResponseContextImpl containerResponseContext;
private String method; // used to hold the explicitly set method performed by a ContainerRequestFilter
private String originalMethod; // store the original method as obtaining it from Vert.x isn't dirt cheap
// this is only set if we override the requestUri
private String path;
// this is cached, but only if we override the requestUri
private String absoluteUri;
// this is only set if we override the requestUri
private String scheme;
// this is only set if we override the requestUri
private String authority;
private String remaining;
private EncodedMediaType responseContentType;
private MediaType consumesMediaType;
private Annotation[] methodAnnotations;
private Annotation[] additionalAnnotations; // can be added by entity annotations or response filters
private Annotation[] allAnnotations;
private Type genericReturnType;
/**
* The input stream, if an entity is present.
*/
private InputStream inputStream;
/**
* used for {@link UriInfo#getMatchedURIs()}
*/
private List<UriMatch> matchedURIs;
private AsyncResponseImpl asyncResponse;
private SseEventSinkImpl sseEventSink;
private List<PathSegment> pathSegments;
private ReaderInterceptor[] readerInterceptors;
private WriterInterceptor[] writerInterceptors;
private SecurityContext securityContext;
private OutputStream outputStream;
private OutputStream underlyingOutputStream;
private FormData formData;
public ResteasyReactiveRequestContext(Deployment deployment, ProvidersImpl providers,
ThreadSetupAction requestContext, ServerRestHandler[] handlerChain, ServerRestHandler[] abortHandlerChain) {
super(handlerChain, abortHandlerChain, requestContext);
this.deployment = deployment;
this.providers = providers;
this.parameters = EMPTY_ARRAY;
}
public abstract ServerHttpRequest serverRequest();
public abstract ServerHttpResponse serverResponse();
public Deployment getDeployment() {
return deployment;
}
public ProvidersImpl getProviders() {
return providers;
}
/**
* Restarts handler chain processing with a new chain targeting a new resource.
*
* @param target The resource target
*/
public void restart(RuntimeResource target) {
restart(target, false);
}
public void restart(RuntimeResource target, boolean setLocatorTarget) {
this.handlers = target.getHandlerChain();
position = 0;
parameters = target.getParameterTypes().length == 0 ? EMPTY_ARRAY : new Object[target.getParameterTypes().length];
if (setLocatorTarget) {
previousResource = new PreviousResource(this.target, pathParamValues, previousResource);
}
this.target = target;
}
/**
* Meant to be used when an error occurred early in processing chain
*/
@Override
public void abortWith(Response response) {
setResult(response);
setAbortHandlerChainStarted(true);
restart(getAbortHandlerChain());
// this is a valid action after suspend, in which case we must resume
if (isSuspended()) {
resume();
}
}
/**
* Resets the build time serialization assumptions. Called if a filter
* modifies the response
*/
public void resetBuildTimeSerialization() {
entityWriter = deployment.getDynamicEntityWriter();
}
public UriInfo getUriInfo() {
if (uriInfo == null) {
uriInfo = new UriInfoImpl(this);
}
return uriInfo;
}
public HttpHeadersImpl getHttpHeaders() {
if (httpHeaders == null) {
httpHeaders = new HttpHeadersImpl(serverRequest().getAllRequestHeaders());
}
return httpHeaders;
}
public Object[] getParameters() {
return parameters;
}
public void setMaxPathParams(int maxPathParams) {
if (maxPathParams > 1) {
pathParamValues = new String[maxPathParams];
} else {
pathParamValues = null;
}
}
public String getPathParam(int index) {
return doGetPathParam(index, pathParamValues);
}
private String doGetPathParam(int index, Object pathParamValues) {
if (pathParamValues instanceof String[]) {
return ((String[]) pathParamValues)[index];
}
if (index > 1) {
throw new IndexOutOfBoundsException();
}
return (String) pathParamValues;
}
public ResteasyReactiveRequestContext setPathParamValue(int index, String value) {
if (pathParamValues instanceof String[]) {
((String[]) pathParamValues)[index] = value;
} else {
if (index > 1) {
throw new IndexOutOfBoundsException();
}
pathParamValues = value;
}
return this;
}
public void setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
public Object getRequestEntity() {
return requestEntity;
}
public ResteasyReactiveRequestContext setRequestEntity(Object requestEntity) {
this.requestEntity = requestEntity;
return this;
}
public EntityWriter getEntityWriter() {
return entityWriter;
}
public ResteasyReactiveRequestContext setEntityWriter(EntityWriter entityWriter) {
this.entityWriter = entityWriter;
return this;
}
public Object getEndpointInstance() {
return endpointInstance;
}
public ResteasyReactiveRequestContext setEndpointInstance(Object endpointInstance) {
this.endpointInstance = endpointInstance;
return this;
}
public Object getResult() {
return result;
}
public Throwable getThrowable() {
return throwable;
}
public Object getResponseEntity() {
Object result = responseEntity();
if (result instanceof GenericEntity) {
return ((GenericEntity<?>) result).getEntity();
}
return result;
}
private Object responseEntity() {
if (response != null && response.isCreated()) {
return response.get().getEntity();
}
return result;
}
public ResteasyReactiveRequestContext setResult(Object result) {
this.result = result;
if (result instanceof Response) {
this.response = new LazyResponse.Existing((Response) result);
} else if (result instanceof GenericEntity) {
setGenericReturnType(((GenericEntity<?>) result).getType());
}
return this;
}
public boolean handlesUnmappedException() {
return true;
}
public void handleUnmappedException(Throwable throwable) {
setResult(Response.serverError().build());
}
public RuntimeResource getTarget() {
return target;
}
public void mapExceptionIfPresent() {
// this is called from the abort chain, but we can abort because we have a Response, or because
// we got an exception
if (throwable != null) {
this.responseContentType = null;
deployment.getExceptionMapper().mapException(throwable, this);
// NOTE: keep the throwable around for close() AsyncResponse notification
}
}
private void sendInternalError(Throwable throwable) {
log.error("Request failed", throwable);
serverResponse().setStatusCode(500).end();
close();
}
@Override
public void close() {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.debug("Failed to close stream", e);
}
try {
if (underlyingOutputStream != null) {
underlyingOutputStream.close();
}
} catch (IOException e) {
log.debug("Failed to close stream", e);
}
super.close();
}
public LazyResponse getResponse() {
return response;
}
public ResteasyReactiveRequestContext setResponse(LazyResponse response) {
this.response = response;
return this;
}
public Request getRequest() {
if (request == null) {
request = new RequestImpl(this);
}
return request;
}
public ContainerRequestContextImpl getContainerRequestContext() {
if (containerRequestContext == null) {
containerRequestContext = new ContainerRequestContextImpl(this);
}
return containerRequestContext;
}
public ContainerResponseContextImpl getContainerResponseContext() {
if (containerResponseContext == null) {
containerResponseContext = new ContainerResponseContextImpl(this);
}
return containerResponseContext;
}
public String getMethod() {
if (method == null) {
if (originalMethod != null) {
return originalMethod;
}
return originalMethod = serverRequest().getRequestMethod();
}
return method;
}
public void setMethod(String method) {
this.method = method;
}
public void setRemaining(String remaining) {
this.remaining = remaining;
}
public String getRemaining() {
return remaining;
}
/**
* Returns the normalised non-decoded path excluding any prefix.
*/
public String getPathWithoutPrefix() {
String path = getPath();
if (path != null) {
String prefix = deployment.getPrefix();
if (!prefix.isEmpty()) {
// FIXME: can we really have paths that don't start with the prefix if there's a prefix?
if (path.startsWith(prefix)) {
return path.substring(prefix.length());
}
}
}
return path;
}
/**
* Returns the normalised non-decoded path including any prefix.
*/
public String getPath() {
if (path == null) {
return serverRequest().getRequestNormalisedPath();
}
return path;
}
public String getAbsoluteURI() {
// if we never changed the path we can use the vert.x URI
if (path == null)
return serverRequest().getRequestAbsoluteUri();
// Note: we could store our cache as normalised, but I'm not sure if the vertx one is normalised
if (absoluteUri == null) {
try {
absoluteUri = new URI(scheme, authority, path, null, null).toASCIIString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
return absoluteUri;
}
public String getScheme() {
if (scheme == null)
return serverRequest().getRequestScheme();
return scheme;
}
public String getAuthority() {
if (authority == null)
return serverRequest().getRequestHost();
return authority;
}
public ResteasyReactiveRequestContext setRequestUri(URI requestURI) {
this.path = requestURI.getPath();
this.authority = requestURI.getRawAuthority();
this.scheme = requestURI.getScheme();
// FIXME: it's possible we may have to also update the query part
// invalidate those
this.uriInfo = null;
this.absoluteUri = null;
return this;
}
/**
* Returns the current response content type. If a response has been set and has an
* explicit content type then this is used, otherwise it returns any content type
* that has been explicitly set.
*/
@Override
public EncodedMediaType getResponseContentType() {
if (response != null) {
if (response.isCreated()) {
MediaType mediaType = response.get().getMediaType();
if (mediaType != null) {
return new EncodedMediaType(mediaType);
}
}
}
return responseContentType;
}
@Override
public MediaType getResponseMediaType() {
EncodedMediaType resp = getResponseContentType();
if (resp == null) {
return null;
}
return resp.mediaType;
}
public ResteasyReactiveRequestContext setResponseContentType(EncodedMediaType responseContentType) {
this.responseContentType = responseContentType;
return this;
}
public ResteasyReactiveRequestContext setResponseContentType(MediaType responseContentType) {
if (responseContentType == null) {
this.responseContentType = null;
} else {
this.responseContentType = new EncodedMediaType(responseContentType);
}
return this;
}
public MediaType getConsumesMediaType() {
return consumesMediaType;
}
public ResteasyReactiveRequestContext setConsumesMediaType(MediaType consumesMediaType) {
this.consumesMediaType = consumesMediaType;
return this;
}
public Annotation[] getAllAnnotations() {
if (allAnnotations == null) {
Annotation[] methodAnnotations = getMethodAnnotations();
if ((additionalAnnotations == null) || (additionalAnnotations.length == 0)) {
allAnnotations = methodAnnotations;
} else {
List<Annotation> list = new ArrayList<>(methodAnnotations.length + additionalAnnotations.length);
list.addAll(Arrays.asList(methodAnnotations));
list.addAll(Arrays.asList(additionalAnnotations));
allAnnotations = list.toArray(new Annotation[0]);
}
}
return allAnnotations;
}
public void setAllAnnotations(Annotation[] annotations) {
this.allAnnotations = annotations;
}
public Annotation[] getMethodAnnotations() {
if (methodAnnotations == null) {
if (target == null) {
return null;
}
return target.getLazyMethod().getAnnotations();
}
return methodAnnotations;
}
public ResteasyReactiveRequestContext setMethodAnnotations(Annotation[] methodAnnotations) {
this.methodAnnotations = methodAnnotations;
return this;
}
public Annotation[] getAdditionalAnnotations() {
return additionalAnnotations;
}
public void setAdditionalAnnotations(Annotation[] additionalAnnotations) {
this.additionalAnnotations = additionalAnnotations;
}
public boolean hasGenericReturnType() {
return this.genericReturnType != null;
}
public Type getGenericReturnType() {
if (genericReturnType == null) {
if (target == null) {
return null;
}
return target.getLazyMethod().getGenericReturnType();
}
return genericReturnType;
}
public ResteasyReactiveRequestContext setGenericReturnType(Type genericReturnType) {
this.genericReturnType = genericReturnType;
return this;
}
public AsyncResponseImpl getAsyncResponse() {
return asyncResponse;
}
public ResteasyReactiveRequestContext setAsyncResponse(AsyncResponseImpl asyncResponse) {
if (this.asyncResponse != null) {
throw new RuntimeException("Async can only be started once");
}
this.asyncResponse = asyncResponse;
return this;
}
public ReaderInterceptor[] getReaderInterceptors() {
return readerInterceptors;
}
public ResteasyReactiveRequestContext setReaderInterceptors(ReaderInterceptor[] readerInterceptors) {
this.readerInterceptors = readerInterceptors;
return this;
}
public WriterInterceptor[] getWriterInterceptors() {
return writerInterceptors;
}
public ResteasyReactiveRequestContext setWriterInterceptors(WriterInterceptor[] writerInterceptors) {
this.writerInterceptors = writerInterceptors;
return this;
}
protected void handleUnrecoverableError(Throwable throwable) {
log.error("Request failed", throwable);
if (serverResponse().headWritten()) {
serverRequest().closeConnection();
} else {
serverResponse().setStatusCode(500).end();
}
close();
}
protected void handleRequestScopeActivation() {
CurrentRequestManager.set(this);
}
@Override
protected void requestScopeDeactivated() {
CurrentRequestManager.set(null);
}
@Override
protected void restarted(boolean keepTarget) {
parameters = EMPTY_ARRAY;
if (!keepTarget) {
target = null;
}
}
public void saveUriMatchState() {
if (matchedURIs == null) {
matchedURIs = new LinkedList<>();
} else if (matchedURIs.get(0).resource == target) {
//already saved
return;
}
if (target != null) {
URITemplate classPath = target.getClassPath();
if (classPath != null) {
//this is not great, but the alternative is to do path based matching on every request
//given that this method is likely to be called very infrequently it is better to have a small
//cost here than a cost applied to every request
int pos = classPath.stem.length();
String path = getPathWithoutPrefix();
//we already know that this template matches, we just need to find the matched bit
for (int i = 1; i < classPath.components.length; ++i) {
URITemplate.TemplateComponent segment = classPath.components[i];
if (segment.type == URITemplate.Type.LITERAL) {
pos += segment.literalText.length();
} else if (segment.type == URITemplate.Type.DEFAULT_REGEX) {
for (; pos < path.length(); ++pos) {
if (path.charAt(pos) == '/') {
--pos;
break;
}
}
} else {
Matcher matcher = segment.pattern.matcher(path);
if (matcher.find(pos) && matcher.start() == pos) {
pos = matcher.end();
}
}
}
matchedURIs.add(new UriMatch(path.substring(1, pos), null, null));
}
}
// FIXME: this may be better as context.normalisedPath() or getPath()
// TODO: does this entry make sense when target is null ?
String path = serverRequest().getRequestPath();
if (path.equals(remaining)) {
matchedURIs.add(0, new UriMatch(path.substring(1), target, endpointInstance));
} else {
matchedURIs.add(0, new UriMatch(path.substring(1, path.length() - (remaining == null ? 0 : remaining.length())),
target, endpointInstance));
}
}
public List<UriMatch> getMatchedURIs() {
saveUriMatchState();
return matchedURIs;
}
public boolean hasInputStream() {
return inputStream != null;
}
public InputStream getInputStream() {
if (inputStream == null) {
inputStream = serverRequest().createInputStream();
}
return inputStream;
}
public ResteasyReactiveRequestContext setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
return this;
}
public SseEventSinkImpl getSseEventSink() {
return sseEventSink;
}
public void setSseEventSink(SseEventSinkImpl sseEventSink) {
this.sseEventSink = sseEventSink;
}
/**
* Return the path segments
* <p>
* This is lazily initialized
*/
public List<PathSegment> getPathSegments() {
if (pathSegments == null) {
initPathSegments();
}
return pathSegments;
}
/**
* initializes the path seegments and removes any matrix params for the path
* used for matching.
*/
public void initPathSegments() {
if (pathSegments != null) {
return;
}
//this is not super optimised
//I don't think we care about it that much though
String path = getPath();
String[] parts = path.split("/");
pathSegments = new ArrayList<>();
boolean hasMatrix = false;
for (String i : parts) {
if (i.isEmpty()) {
continue;
}
PathSegmentImpl ps = new PathSegmentImpl(i, true);
hasMatrix = ps.hasMatrixParams() || hasMatrix;
pathSegments.add(ps);
}
if (hasMatrix) {
StringBuilder sb = new StringBuilder();
for (PathSegment i : pathSegments) {
sb.append("/");
sb.append(i.getPath());
}
if (path.endsWith("/")) {
sb.append("/");
}
String newPath = sb.toString();
this.path = newPath;
if (this.remaining != null) {
this.remaining = newPath.substring(getPathWithoutPrefix().length() - this.remaining.length());
}
}
}
@Override
public Object getHeader(String name, boolean single) {
if (httpHeaders == null) {
if (single)
return serverRequest().getRequestHeader(name);
// empty collections must not be turned to null
return serverRequest().getAllRequestHeaders(name);
} else {
if (single)
return httpHeaders.getMutableHeaders().getFirst(name);
// empty collections must not be turned to null
List<String> list = httpHeaders.getMutableHeaders().get(name);
if (list == null) {
return Collections.emptyList();
} else {
return list;
}
}
}
@Override
public Object getQueryParameter(String name, boolean single, boolean encoded) {
if (single) {
String val = serverRequest().getQueryParam(name);
if (encoded && val != null) {
val = Encode.encodeQueryParam(val);
}
return val;
}
// empty collections must not be turned to null
List<String> strings = serverRequest().getAllQueryParams(name);
if (encoded) {
List<String> newStrings = new ArrayList<>();
for (String i : strings) {
newStrings.add(Encode.encodeQueryParam(i));
}
return newStrings;
}
return strings;
}
@Override
public Object getMatrixParameter(String name, boolean single, boolean encoded) {
if (single) {
for (PathSegment i : getPathSegments()) {
String res = i.getMatrixParameters().getFirst(name);
if (res != null) {
if (encoded) {
return Encode.encodeQueryParam(res);
}
return res;
}
}
return null;
} else {
List<String> ret = new ArrayList<>();
for (PathSegment i : getPathSegments()) {
List<String> res = i.getMatrixParameters().get(name);
if (res != null) {
if (encoded) {
for (String j : res) {
ret.add(Encode.encodeQueryParam(j));
}
} else {
ret.addAll(res);
}
}
}
// empty collections must not be turned to null
return ret;
}
}
@Override
public String getCookieParameter(String name) {
Cookie cookie = getHttpHeaders().getCookies().get(name);
return cookie != null ? cookie.getValue() : null;
}
@Override
public Object getFormParameter(String name, boolean single, boolean encoded) {
if (formData == null) {
return null;
}
if (single) {
FormData.FormValue val = formData.getFirst(name);
if (val == null || val.isFileItem()) {
return null;
}
if (encoded) {
return Encode.encodeQueryParam(val.getValue());
}
return val.getValue();
}
Deque<FormData.FormValue> val = formData.get(name);
List<String> strings = new ArrayList<>();
if (val != null) {
for (FormData.FormValue i : val) {
if (encoded) {
strings.add(Encode.encodeQueryParam(i.getValue()));
} else {
strings.add(i.getValue());
}
}
}
return strings;
}
@Override
public String getPathParameter(String name, boolean encoded) {
// this is a slower version than getPathParam, but we can't actually bake path indices inside
// BeanParam classes (which use thismethod ) because they can be used by multiple resources that would have different
// indices
Integer index = target.getPathParameterIndexes().get(name);
String value;
if (index != null) {
value = getPathParam(index);
} else {
// Check previous resources if the path is not defined in the current target
value = getResourceLocatorPathParam(name);
}
// It's possible to inject a path param that's not defined, return null in this case
if (encoded && value != null) {
return Encode.encodeQueryParam(value);
}
return value;
}
public <T> T unwrap(Class<T> type) {
return serverRequest().unwrap(type);
}
public SecurityContext getSecurityContext() {
if (securityContext == null) {
securityContext = createSecurityContext();
}
return securityContext;
}
public boolean isSecurityContextSet() {
return securityContext != null;
}
protected SecurityContext createSecurityContext() {
throw new UnsupportedOperationException();
}
public ResteasyReactiveRequestContext setSecurityContext(SecurityContext securityContext) {
this.securityContext = securityContext;
securityContextUpdated(securityContext);
return this;
}
protected void securityContextUpdated(SecurityContext securityContext) {
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
public OutputStream getOrCreateOutputStream() {
if (outputStream == null) {
return outputStream = underlyingOutputStream = serverResponse().createResponseOutputStream();
}
return outputStream;
}
@Override
public ResteasyReactiveResourceInfo getResteasyReactiveResourceInfo() {
return target == null ? null : target.getLazyMethod();
}
@Override
protected abstract Executor getEventLoop();
public abstract Runnable registerTimer(long millis, Runnable task);
public String getResourceLocatorPathParam(String name) {
return getResourceLocatorPathParam(name, previousResource);
}
public FormData getFormData() {
return formData;
}
public ResteasyReactiveRequestContext setFormData(FormData formData) {
this.formData = formData;
return this;
}
private String getResourceLocatorPathParam(String name, PreviousResource previousResource) {
if (previousResource == null) {
return null;
}
int index = 0;
URITemplate classPath = previousResource.locatorTarget.getClassPath();
if (classPath != null) {
for (URITemplate.TemplateComponent component : classPath.components) {
if (component.name != null) {
if (component.name.equals(name)) {
return doGetPathParam(index, previousResource.locatorPathParamValues);
}
index++;
} else if (component.names != null) {
for (String nm : component.names) {
if (nm.equals(name)) {
return doGetPathParam(index, previousResource.locatorPathParamValues);
}
}
index++;
}
}
}
for (URITemplate.TemplateComponent component : previousResource.locatorTarget.getPath().components) {
if (component.name != null) {
if (component.name.equals(name)) {
return doGetPathParam(index, previousResource.locatorPathParamValues);
}
index++;
} else if (component.names != null) {
for (String nm : component.names) {
if (nm.equals(name)) {
return doGetPathParam(index, previousResource.locatorPathParamValues);
}
}
index++;
}
}
return getResourceLocatorPathParam(name, previousResource.prev);
}
public abstract boolean resumeExternalProcessing();
static class PreviousResource {
public PreviousResource(RuntimeResource locatorTarget, Object locatorPathParamValues, PreviousResource prev) {
this.locatorTarget = locatorTarget;
this.locatorPathParamValues = locatorPathParamValues;
this.prev = prev;
}
/**
* When a subresource has been located and the processing has been restarted (and thus target point to the new
* subresource),
* this field contains the target that resulted in the offloading to the new target
*/
private final RuntimeResource locatorTarget;
/**
* When a subresource has been located and the processing has been restarted (and thus target point to the new
* subresource),
* this field contains the pathParamValues of the target that resulted in the offloading to the new target
*/
private final Object locatorPathParamValues;
private final PreviousResource prev;
}
}
|
package org.jsimpledb.kv.array;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
import org.jsimpledb.kv.KVPair;
import org.jsimpledb.util.ByteUtil;
/**
* Performs searches into an {@link ArrayKVStore}.
*
* <p>
* Instances are not thread safe.
*/
class ArrayKVFinder {
private final ByteBuffer indx;
private final ByteBuffer keys;
private final ByteBuffer vals;
private final int size;
ArrayKVFinder(ByteBuffer indx, ByteBuffer keys, ByteBuffer vals) {
Preconditions.checkArgument(indx.capacity() % 8 == 0, "index size is not a multiple of 8");
this.indx = indx.duplicate();
this.keys = keys.duplicate();
this.vals = vals.duplicate();
this.indx.limit(this.indx.capacity());
this.keys.limit(this.keys.capacity());
this.vals.limit(this.vals.capacity());
this.size = this.indx.capacity() / 8;
}
/**
* Search for the index of the entry with the given key.
*
* @return maching index, or ones complement of insertion point if not found
*/
public int find(byte[] searchKey) {
// Initialize bounds using cached prefix
int min = 0;
int max = this.size;
// Perform binary search for key, starting at the point where we diverged from the previous search key
byte[] prevMin = null;
byte[] prevMax = null;
while (min < max) {
// Calculate the midpoint of the search range
final int mid = (min + (max - 1)) >>> 1;
// Get key at midpoint
final byte[] midKey = this.readKey(mid);
assert prevMin == null || ByteUtil.compare(searchKey, prevMin) > 0;
assert prevMax == null || ByteUtil.compare(searchKey, prevMax) < 0;
// Compare search key to the midpoint key
final int diff = ByteUtil.compare(searchKey, midKey);
if (diff == 0)
return mid;
if (diff < 0) {
prevMax = midKey;
max = mid;
} else {
prevMin = midKey;
min = mid + 1;
}
}
// Key was not found
return ~min;
}
/**
* Read the key at the specified index.
*/
public byte[] readKey(int index) {
// Sanity check
Preconditions.checkArgument(index >= 0, "index < 0");
Preconditions.checkArgument(index < this.size, "index >= size");
// If this is a base key, read absolute offset and fetch data normally
final int baseIndex = index & ~0x1f;
final int baseKeyOffset = this.indx.getInt(baseIndex * 8);
if (index == baseIndex) {
final int length = (index + 1) < this.size ?
this.indx.getInt((index + 1) * 8) & 0x00ffffff : this.keys.capacity() - baseKeyOffset;
final byte[] data = new byte[length];
this.keys.position(baseKeyOffset);
this.keys.get(data);
return data;
}
// Read the base key absolute offset, then encoded key prefix length and relative suffix offset
final int encodedValue = this.indx.getInt(index * 8);
final int prefixLen = encodedValue >>> 24;
final int suffixOffset = baseKeyOffset + (encodedValue & 0x00ffffff);
// Calculate the start of the following key in order to determine this key's suffix length
final int nextIndex = index + 1;
int nextOffset;
if (nextIndex < this.size) {
nextOffset = this.indx.getInt(nextIndex * 8);
if ((nextIndex & 0x1f) != 0)
nextOffset = baseKeyOffset + (nextOffset & 0x00ffffff);
} else
nextOffset = this.keys.capacity();
final int suffixLen = nextOffset - suffixOffset;
// Fetch the key in two parts, prefix then suffix
final byte[] key = new byte[prefixLen + suffixLen];
if (prefixLen > 0) {
this.keys.position(baseKeyOffset);
this.keys.get(key, 0, prefixLen);
}
assert suffixLen > 0;
this.keys.position(suffixOffset);
this.keys.get(key, prefixLen, suffixLen);
return key;
}
/**
* Read the value at the specified index.
*/
public byte[] readValue(int index) {
Preconditions.checkArgument(index >= 0, "index < 0");
Preconditions.checkArgument(index < this.size, "index >= size");
final int dataOffset = this.indx.getInt(index * 8 + 4);
final int nextOffset = (index + 1) < this.size ? this.indx.getInt((index + 1) * 8 + 4) : this.vals.capacity();
final int length = nextOffset - dataOffset;
final byte[] data = new byte[length];
this.vals.position(dataOffset);
this.vals.get(data);
return data;
}
/**
* Read the key/value pair at the specified index.
*/
public KVPair readKV(int index) {
return new KVPair(this.readKey(index), this.readValue(index));
}
}
|
package com.qpark.maven.plugin.objectfactories;
import java.io.File;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.xml.namespace.QName;
import org.apache.maven.plugin.logging.Log;
import com.qpark.maven.Util;
import com.qpark.maven.xmlbeans.ComplexType;
import com.qpark.maven.xmlbeans.ElementType;
import com.qpark.maven.xmlbeans.XsdContainer;
import com.qpark.maven.xmlbeans.XsdsUtil;
/**
* Generates a ServiceObjectFactory out of the XSDs containing elements.
*
* @author bhausen
*/
@Deprecated
public class ServiceObjectFactoryGenerator {
/** Parsed complex types. */
private final TreeSet<ElementType> elementTypes;
/** The {@link Log}. */
private final Log log;
/** The {@link XsdsUtil}. */
private final XsdsUtil xsds;
/** The output directory. */
private final File outputDirectory;
private final String messagePackageNameSuffix;
/**
* @param config
* @param complexTypes
*/
public ServiceObjectFactoryGenerator(final XsdsUtil xsds, final File outputDirectory,
final String messagePackageNameSuffix, final Log log) {
this.xsds = xsds;
this.outputDirectory = outputDirectory;
if (messagePackageNameSuffix != null && messagePackageNameSuffix.trim().length() > 0) {
this.messagePackageNameSuffix = messagePackageNameSuffix;
} else {
this.messagePackageNameSuffix = "msg restmsg";
}
this.log = log;
this.elementTypes = xsds.getElementTypes();
}
public void generate() {
this.log.debug("+generate");
StringBuffer imports = new StringBuffer();
TreeSet<String> contextPath = new TreeSet<String>();
StringBuffer methods = new StringBuffer();
StringBuffer objectFactories = new StringBuffer();
imports.append("\nimport javax.xml.bind.JAXBElement;\n");
// imports.append("\nimport
// org.springframework.stereotype.Component;\n");
TreeMap<String, String> importedModels = new TreeMap<String, String>();
for (Entry<String, XsdContainer> xx : this.xsds.getXsdContainerMap().entrySet()) {
if (XsdsUtil.isMessagePackageName(xx.getValue().getPackageName(), this.messagePackageNameSuffix)) {
for (String imp : xx.getValue().getImportedTargetNamespaces()) {
importedModels.put(xx.getKey(), xx.getValue().getFile().getAbsolutePath());
}
}
}
TreeMap<String, String> ofMap = new TreeMap<String, String>();
TreeSet<String> methodNames = new TreeSet<String>();
ComplexType ct;
String ofName;
String eName;
String pOfName;
String mName;
for (ElementType element : this.elementTypes) {
if (XsdsUtil.isMessagePackageName(element.getPackageName(), this.messagePackageNameSuffix)) {
pOfName = element.getPackageName();
contextPath.add(pOfName);
ofName = ofMap.get(pOfName);
if (ofName == null) {
ofName = pOfName.replace('.', '_');
objectFactories.append("\n\tprivate ").append(pOfName).append(".ObjectFactory ").append(ofName)
.append(" = new ").append(pOfName).append(".ObjectFactory();");
ofMap.put(pOfName, ofName);
}
eName = element.getClassNameObject();
this.log.debug("new ComplexType " + element.getElement().getType());
this.log.debug(" packagename " + this.xsds.getPackageName(element.getElement().getType().getName()));
ct = new ComplexType(element.getElement().getType(), this.xsds);
if (ct.getPackageName().length() > 0) {
// imports.append("\nimport ")
// .append(ct.getClassNameFullQualified()).append(";");
mName = new StringBuffer(6 + eName.length()).append("create").append(eName).toString();
if (methodNames.contains(mName)) {
mName = new StringBuffer(6 + eName.length() + pOfName.length()).append("create")
.append(Util.capitalizePackageName(pOfName)).append(eName).toString();
}
methodNames.add(mName);
methods.append("\n\t/**");
methods.append("\n\t * @param value a {@link ");
methods.append(ct.getClassNameFullQualified());
methods.append("}");
methods.append("\n\t * @return a new {@link JAXBElement} containing a {@link ");
methods.append(ct.getClassNameFullQualified());
methods.append("}");
methods.append("\n\t * @see ");
methods.append(pOfName);
methods.append(".ObjectFactory#create");
methods.append(eName);
methods.append("(");
methods.append(ct.getClassNameFullQualified());
methods.append(")");
methods.append("\n\t */");
methods.append("\n\tpublic JAXBElement<");
methods.append(ct.getClassNameFullQualified());
methods.append("> ").append(mName);
methods.append("(final ");
methods.append(ct.getClassNameFullQualified());
methods.append(" value) {");
methods.append("\n\t\treturn this.");
methods.append(ofName).append(".create");
methods.append(eName);
methods.append("(value);");
methods.append("\n\t}\n");
}
}
}
QName tns;
String cName;
String pName;
String mOfName;
for (ComplexType type : this.xsds.getComplexTypes()) {
if (XsdsUtil.isMessagePackageName(type.getPackageName(), this.messagePackageNameSuffix)) {
tns = type.getType().getName();
if (!type.isAbstractType() && !type.isEnumType() && !type.isSimpleType() && !type.isPrimitiveType()
&& (tns == null || importedModels.containsKey(tns.getNamespaceURI()))) {
pName = type.getPackageName();
ofName = ofMap.get(pName);
if (ofName == null) {
ofName = pName.replace('.', '_');
objectFactories.append("\n\tprivate ").append(pName).append(".ObjectFactory ").append(ofName)
.append(" = new ").append(pName).append(".ObjectFactory();");
ofMap.put(pName, ofName);
}
cName = type.getClassName();
mName = new StringBuffer(6 + cName.length()).append("create").append(cName).toString()
.replaceAll("\\.", "");
mOfName = mName;
cName = type.getClassNameFullQualified();
if (methodNames.contains(mName)) {
mName = new StringBuffer(6 + cName.length() + pName.length()).append("create")
.append(Util.capitalizePackageName(pName)).append(cName).toString()
.replaceAll("\\.", "");
}
methodNames.add(mName);
methods.append("\n\t/**\n\t * @return a new {@link ");
methods.append(cName);
methods.append("}");
methods.append("\n\t * @see ");
methods.append(pName);
methods.append(".ObjectFactory#");
methods.append(mOfName);
methods.append("\n\t */");
methods.append("\n\tpublic ");
methods.append(cName).append(" ");
methods.append(mName);
methods.append("() {");
methods.append("\n\t\treturn this.");
methods.append(ofName);
methods.append(".");
methods.append(mOfName);
methods.append("();");
methods.append("\n\t}\n");
}
}
}
File f = Util.getFile(this.outputDirectory, this.xsds.getBasePackageName(), "ServiceObjectFactory.java");
this.log.info(new StringBuffer().append("Write ").append(f.getAbsolutePath()));
try {
StringBuffer sb = new StringBuffer(1024);
sb.append("package ");
sb.append(this.xsds.getBasePackageName());
sb.append(";\n\n");
sb.append("\n");
sb.append(imports.toString());
sb.append("\n");
sb.append(
"\n/**\n * The ServiceObjectFactory contains the creation of all JAXBElement's defined\n * in the XSDs and extends the ModelObjectFactory.\n");
sb.append(" * <pre>");
sb.append(Util.getGeneratedAt());
sb.append("</pre>\n");
sb.append(" * @author bhausen\n");
sb.append(" */\n");
// sb.append("@Component\n");
sb.append("public class ServiceObjectFactory extends ModelObjectFactory {");
sb.append("\n\tpublic static final String CONTEXT_PATH_DEFINITON =\"");
for (int i = 0; i < contextPath.size(); i++) {
if (i > 0) {
sb.append(":");
}
sb.append(contextPath.toArray()[i]);
}
sb.append("\";");
sb.append(objectFactories.toString());
sb.append("\n");
sb.append(methods.toString());
sb.append("}");
Util.writeToFile(f, sb.toString());
} catch (Exception e) {
this.log.error(e.getMessage());
e.printStackTrace();
}
this.log.debug("-generate");
}
}
|
package org.languagetool.language;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.Languages;
import org.languagetool.databroker.ResourceDataBroker;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
/**
* Information about common words - use as a fallback if language identification yields low confidence.
* @since 4.4
*/
public class CommonWords {
private final static Map<String, List<Language>> word2langs = Collections.synchronizedMap(new HashMap<>());
private final static Pattern numberPattern = Pattern.compile("[0-9.,%-]+");
public CommonWords() throws IOException {
if (word2langs.isEmpty()) {
for (Language lang : Languages.get()) {
if (lang.isVariant()) {
continue;
}
ResourceDataBroker dataBroker = JLanguageTool.getDataBroker();
String path = lang.getCommonWordsPath();
InputStream stream = null;
try {
if (path != null) {
if (dataBroker.resourceExists(path)) {
stream = dataBroker.getFromResourceDirAsStream(path);
} else if (new File(path).exists()) {
stream = new FileInputStream(path);
} else {
throw new IOException("Common words file not found for " + lang + ": " + path);
}
} else {
System.out.println("WARN: no common words file defined for " + lang + " - this language might not be correctly auto-detected");
continue;
}
try (Scanner scanner = new Scanner(stream, "utf-8")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty() || line.startsWith("
continue;
}
String key = line.toLowerCase();
List<Language> languages = word2langs.get(key);
if (languages == null) {
// word2langs is static, so this can be accessed from multiple threads concurrently -> prevent exceptions
List<Language> l = Collections.synchronizedList(new LinkedList<>());
l.add(lang);
word2langs.put(key, l);
} else {
languages.add(lang);
}
}
}
} finally {
if (stream != null) {
stream.close();
}
}
}
}
}
public Map<Language, Integer> getKnownWordsPerLanguage(String text) {
Map<Language,Integer> result = new HashMap<>();
if (!text.endsWith(" ")) {
// last word might not be finished yet, so ignore
text = text.replaceFirst("\\p{L}+$", "");
}
// Proper per-language tokenizing might help, but then the common_words.txt
// will also need to be tokenized the same way. Also, this is quite fast.
String[] words = text.split("[(),.:;!?„“\"¡¿\\s-]");
for (String word : words) {
if (numberPattern.matcher(word).matches()) {
continue;
}
List<Language> languages = word2langs.get(word.toLowerCase());
if (languages != null) {
for (Language lang : languages) {
if (result.containsKey(lang)) {
result.put(lang, result.get(lang) + 1);
} else {
result.put(lang, 1);
}
}
}
}
return result;
}
}
|
package org.languagetool.markup;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A text with markup and with a mapping so error positions will refer to the original
* position that includes the markup, even though only the plain text parts are checked.
* Use {@link AnnotatedTextBuilder} to create objects of this type.
* @since 2.3
*/
public class AnnotatedText {
/**
* @since 3.9
*/
public enum MetaDataKey {
DocumentTitle,
EmailToAddress,
EmailNumberOfAttachments
}
private final List<TextPart> parts;
private final Map<Integer, MappingValue> mapping; // plain text position to original text (with markup) position
private final Map<MetaDataKey, String> metaData;
private final Map<String, String> customMetaData;
AnnotatedText(List<TextPart> parts, Map<Integer, MappingValue> mapping, Map<MetaDataKey, String> metaData, Map<String, String> customMetaData) {
this.parts = Objects.requireNonNull(parts);
this.mapping = Objects.requireNonNull(mapping);
this.metaData = Objects.requireNonNull(metaData);
this.customMetaData = Objects.requireNonNull(customMetaData);
}
/**
* Get the plain text, without markup and content from {@code interpretAs}.
* @since 4.3
*/
public String getOriginalText() {
StringBuilder sb = new StringBuilder();
for (TextPart part : parts) {
if (part.getType() == TextPart.Type.TEXT) {
sb.append(part.getPart());
}
}
return sb.toString();
}
/**
* Get the plain text, without markup but with content from {@code interpretAs}.
*/
public String getPlainText() {
StringBuilder sb = new StringBuilder();
for (TextPart part : parts) {
if (part.getType() == TextPart.Type.TEXT || part.getType() == TextPart.Type.FAKE_CONTENT) {
sb.append(part.getPart());
}
}
return sb.toString();
}
/**
* @since 4.3
*/
public String getTextWithMarkup() {
StringBuilder sb = new StringBuilder();
for (TextPart part : parts) {
if (part.getType() != TextPart.Type.FAKE_CONTENT) {
sb.append(part.getPart());
}
}
return sb.toString();
}
/**
* Internally used by LanguageTool to adjust error positions to point to the
* original location with markup, even though markup was ignored during text checking.
* @param plainTextPosition the position in the plain text (no markup) that was checked
* @param isToPos the from/to position needed
* @return an adjusted position of the same location in the text with markup
*/
public int getOriginalTextPositionFor(int plainTextPosition, boolean isToPos) {
if (plainTextPosition < 0) {
throw new IllegalArgumentException("plainTextPosition must be >= 0: " + plainTextPosition);
}
if (mapping.isEmpty()) {
return 0;
}
int minDiff = Integer.MAX_VALUE;
MappingValue bestMatch = null;
// algorithm: find the closest lower position
for (Map.Entry<Integer, MappingValue> entry : mapping.entrySet()) {
int maybeClosePosition = entry.getKey();
if (plainTextPosition < maybeClosePosition) {
int diff = maybeClosePosition - plainTextPosition;
if (diff > 0 && diff < minDiff) {
bestMatch = entry.getValue();
minDiff = diff;
}
}
}
if (bestMatch == null) {
throw new RuntimeException("Could not map " + plainTextPosition + " to original position. isToPos: " + isToPos + ", mappings: " + mapping.size());
}
// we remove markup total length if usage of fake markup and need from position
if (!isToPos && bestMatch.getFakeMarkupLength() > 0) {
minDiff = bestMatch.getFakeMarkupLength();
}
// We assume that when we have found the closest match there's a one-to-one mapping
// in this region, thus we can subtract 'minDiff' to get the exact position.
// If the bestMatch is a fakeMarkup, subtract it:
return bestMatch.getTotalPosition() - minDiff;
}
/**
* @since 3.9
*/
public String getGlobalMetaData(String key, String defaultValue) {
return customMetaData.getOrDefault(key, defaultValue);
}
/**
* @since 3.9
*/
public String getGlobalMetaData(MetaDataKey key, String defaultValue) {
return metaData.getOrDefault(key, defaultValue);
}
@Override
public String toString() {
return StringUtils.join(parts, "");
}
}
|
package com.quemb.qmbform.view;
import com.quemb.qmbform.R;
import com.quemb.qmbform.descriptor.RowDescriptor;
import android.content.Context;
import android.widget.LinearLayout;
public class SeperatorSectionCell extends FormBaseCell {
public SeperatorSectionCell(Context context,
RowDescriptor rowDescriptor) {
super(context, rowDescriptor);
}
public void init() {
super.init();
setOrientation(LinearLayout.VERTICAL);
setClickable(false);
setEnabled(false);
}
@Override
public boolean shouldAddDivider() {
return false;
}
@Override
protected int getResource() {
return R.layout.section_seperator_cell;
}
@Override
protected void update() {
}
}
|
package ca.eandb.sortable;
import java.util.HashMap;
import java.util.Map;
public final class TrieNode {
/**
* A <code>Map</code> used to lookup the children of a particular node.
* This map will be shared by all the <code>TrieNode</code>s for a given
* trie. The key type for this map is the (node, character) pair that
* uniquely identifies the parent-child edge.
*
* @see ChildRef
*/
private final Map<ChildRef, TrieNode> children;
/** The parent <code>TrieNode</code> of this node. */
private final TrieNode parent;
/** An optional data <code>Object</code> associated with this node. */
private Object data;
/**
* Represents a <code>(TrieNode, char)</code> pair that uniquely identifies
* a parent-child edge in the trie.
*/
private static class ChildRef {
/** The parent <code>TrieNode</code>. */
public final TrieNode parent;
/**
* The <code>char</code> that identifies a particular child of the
* parent <code>TreeNode</code>.
*/
public final char character;
/**
* Creates a new <code>ChildRef</code>.
* @param parent The parent <code>TrieNode</code>.
* @param character The <code>char</code> that identifies a particular
* child of the parent <code>TreeNode</code>.
*/
public ChildRef(TrieNode parent, char character) {
this.parent = parent;
this.character = character;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return (obj instanceof ChildRef) && equals((ChildRef) obj);
}
/**
* Determines whether two <code>ChildRef</code>s represent the same
* edge in the trie.
* @param other The <code>ChildRef</code> to compare with this one.
* @return A value indicating if this <code>ChildRef</code> and
* <code>other</code> represent the same edge.
*/
public boolean equals(ChildRef other) {
return parent == other.parent && character == other.character;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return parent.hashCode() ^ new Character(character).hashCode();
}
}
/**
* Creates a new root <code>TrieNode</code>.
*/
public TrieNode() {
this.children = new HashMap<ChildRef, TrieNode>();
this.parent = null;
}
/**
* Creates a new child <code>TrieNode</code>.
* @param parent The parent <code>TrieNode</code> of the new node.
*/
private TrieNode(TrieNode parent) {
/* Nodes in the same trie share a common children map. */
this.children = parent.children;
this.parent = parent;
}
/**
* Creates a new <code>TrieNode</code> which is to be the child of this
* <code>TrieNode</code>.
* @return A new <code>TrieNode</code>.
*/
private TrieNode newChild() {
return new TrieNode(this);
}
/**
* Finds a child of this <code>TrieNode</code>.
* @param c The <code>char</code> identifying which child to find.
* @return The specified child <code>TrieNode</code>, or <code>null</code>
* if no such child exists.
*/
public TrieNode findChild(char c) {
ChildRef ref = new ChildRef(this, c);
return children.get(ref);
}
/**
* Finds a descendant of this <code>TrieNode</code>.
* @param s The <code>String</code> identifying the path to follow.
* @return The specified descendant <code>TrieNode</code>, or
* <code>null</code> if no such descendant exists.
*/
public TrieNode findDescendant(String s) {
TrieNode node = this;
for (int i = 0, n = s.length(); i < n && node != null; i++) {
node = node.findChild(s.charAt(i));
}
return node;
}
/**
* Inserts a child <code>TrieNode</code> into the trie.
* @param c The <code>char</code> identifying the new child.
* @return The new child <code>TrieNode</code>, or the existing child if
* one already exists corresponding to <code>c</code>.
*/
public TrieNode insert(char c) {
TrieNode child = findChild(c);
if (child == null) {
ChildRef ref = new ChildRef(this, c);
child = newChild();
children.put(ref, child);
}
return child;
}
/**
* Inserts a chain of descendant <code>TrieNode</code> into the trie.
* @param s The <code>String</code> identifying the path to insert.
* @return The new descendant <code>TrieNode</code> at the end of the path,
* or the existing descendant if one already exists corresponding to
* <code>s</code>.
*/
public TrieNode insert(String s) {
TrieNode node = this;
for (int i = 0, n = s.length(); i < n; i++) {
node = node.insert(s.charAt(i));
}
return node;
}
/**
* Determines if this <code>TrieNode</code> is the root of a trie.
* @return A value indicating if this <code>TrieNode</code> is the root of
* a trie.
*/
public boolean isRoot() {
return parent == null;
}
/**
* Gets the parent <code>TrieNode</code> of this <code>TrieNode</code>.
* @return The parent <code>TrieNode</code> of this <code>TrieNode</code>.
*/
public TrieNode getParent() {
return parent;
}
/**
* Gets the <code>Object</code> associated with this node.
* @return The <code>Object</code> associated with this node.
*/
public Object getData() {
return data;
}
/**
* Sets the <code>Object</code> associated with this node.
* @param data The <code>Object</code> to associate with this node.
*/
public void setData(Object data) {
this.data = data;
}
}
|
package project;
import com.github.sormuras.bach.project.Project;
public class Configurator implements Project.Configurator {
@Override
public Project configure(Project project) {
return project.withVersion("17-M5");
}
}
|
package com.xenonteam.xenonlib.common.networking;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import com.xenonteam.xenonlib.config.Refs;
import com.xenonteam.xenonlib.tileentity.IGenericTileEntity;
import com.xenonteam.xenonlib.util.GenericUtils;
/**
* @author tim4242
* @author philipas
*
*/
@Sharable
public class DescriptionHandler extends SimpleChannelInboundHandler<FMLProxyPacket>{
public static final String CHANNEL = Refs.MOD_ID + "Description";
static {
NetworkRegistry.INSTANCE.newChannel(CHANNEL, new DescriptionHandler());
}
public static void init(){
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FMLProxyPacket msg) throws Exception{
ByteBuf buf = msg.payload();
int x = buf.readInt();
int y = buf.readInt();
int z = buf.readInt();
TileEntity te = GenericUtils.getClientPlayer().worldObj.getTileEntity(new BlockPos(x, y, z));
if(te instanceof IGenericTileEntity) {
((IGenericTileEntity)te).readFromPacket(buf);
}
}
}
|
package io.mangoo.routing.handlers;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.boon.json.JsonFactory;
import org.boon.json.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.inject.Injector;
import freemarker.template.TemplateException;
import io.mangoo.annotations.FilterWith;
import io.mangoo.authentication.Authentication;
import io.mangoo.configuration.Config;
import io.mangoo.core.Application;
import io.mangoo.crypto.Crypto;
import io.mangoo.enums.ContentType;
import io.mangoo.enums.Default;
import io.mangoo.enums.Header;
import io.mangoo.enums.Key;
import io.mangoo.i18n.Messages;
import io.mangoo.interfaces.MangooGlobalFilter;
import io.mangoo.routing.Response;
import io.mangoo.routing.bindings.Body;
import io.mangoo.routing.bindings.Exchange;
import io.mangoo.routing.bindings.Flash;
import io.mangoo.routing.bindings.Form;
import io.mangoo.routing.bindings.Session;
import io.mangoo.templating.TemplateEngine;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.server.handlers.form.FormParserFactory;
import io.undertow.util.HeaderValues;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.StatusCodes;
public class RequestHandler implements HttpHandler {
private static final int AUTH_PREFIX_LENGTH = 2;
private static final int TOKEN_LENGTH = 16;
private static final int INDEX_2 = 2;
private static final int INDEX_1 = 1;
private static final int INDEX_0 = 0;
private static final int SESSION_PREFIX_LENGTH = 3;
private int parameterCount;
private Class<?> controllerClass;
private String controllerMethod;
private Object controller;
private Map<String, Class<?>> parameters;
private Method method;
private ObjectMapper mapper;
private Authentication authentication;
private Session session;
private Flash flash;
private Form form;
private Config config;
private Injector injector;
private Exchange exchange;
private boolean globalFilter;
public RequestHandler(Class<?> controllerClass, String controllerMethod) {
this.injector = Application.getInjector();
this.controllerClass = controllerClass;
this.controllerMethod = controllerMethod;
this.controller = this.injector.getInstance(this.controllerClass);
this.parameters = getMethodParameters();
this.parameterCount = this.parameters.size();
this.config = this.injector.getInstance(Config.class);
this.globalFilter = this.injector.getAllBindings().containsKey(com.google.inject.Key.get(MangooGlobalFilter.class));
this.mapper = JsonFactory.create();
}
@Override
@SuppressWarnings("all")
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (this.method == null) {
this.method = this.controller.getClass().getMethod(this.controllerMethod, parameters.values().toArray(new Class[0]));
}
this.exchange = null;
this.session = null;
this.form = null;
this.authentication = null;
setLocale(exchange);
getSession(exchange);
getAuthentication(exchange);
getFlash(exchange);
getForm(exchange);
boolean continueAfterFilter = executeFilter(exchange);
if (continueAfterFilter) {
Response response = getResponse(exchange);
setSession(exchange);
setFlash(exchange);
setAuthentication(exchange);
if (response.isRedirect()) {
exchange.setResponseCode(StatusCodes.FOUND);
exchange.getResponseHeaders().put(Headers.LOCATION, response.getRedirectTo());
exchange.getResponseHeaders().put(Headers.SERVER, Default.SERVER.toString());
exchange.endExchange();
} else if (response.isBinary()) {
exchange.dispatch(exchange.getDispatchExecutor(), new BinaryHandler(response));
} else {
exchange.setResponseCode(response.getStatusCode());
exchange.getResponseHeaders().put(Header.X_XSS_PPROTECTION.toHttpString(), Default.X_XSS_PPROTECTION.toInt());
exchange.getResponseHeaders().put(Header.X_CONTENT_TYPE_OPTIONS.toHttpString(), Default.NOSNIFF.toString());
exchange.getResponseHeaders().put(Header.X_FRAME_OPTIONS.toHttpString(), Default.SAMEORIGIN.toString());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, response.getContentType() + "; charset=" + response.getCharset());
exchange.getResponseHeaders().put(Headers.SERVER, Default.SERVER.toString());
response.getHeaders().forEach((key, value) -> exchange.getResponseHeaders().add(key, value));
exchange.getResponseSender().send(response.getBody());
}
}
}
private void setLocale(HttpServerExchange exchange) {
HeaderValues headerValues = exchange.getRequestHeaders().get(Headers.ACCEPT_LANGUAGE_STRING);
if (headerValues != null && headerValues.getFirst() != null) {
Iterable<String> split = Splitter.on(",").trimResults().split(headerValues.getFirst());
if (split != null) {
String language = split.iterator().next();
if (StringUtils.isBlank(language)) {
language = this.config.getString(Key.APPLICATION_LANGUAGE, Default.LANGUAGE.toString());
}
Locale.setDefault(Locale.forLanguageTag(language.substring(0, 1)));
Application.getInjector().getInstance(Messages.class).reload();
}
}
}
private boolean executeFilter(HttpServerExchange exchange) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
boolean continueAfterFilter = executeGlobalFilter(exchange);
if (continueAfterFilter) {
continueAfterFilter = executeFilter(this.controllerClass.getAnnotations(), exchange);
}
if (continueAfterFilter) {
continueAfterFilter = executeFilter(this.method.getAnnotations(), exchange);
}
return continueAfterFilter;
}
private boolean executeGlobalFilter(HttpServerExchange exchange) {
if (this.globalFilter) {
MangooGlobalFilter mangooGlobalFilter = this.injector.getInstance(MangooGlobalFilter.class);
return mangooGlobalFilter.filter(getExchange(exchange));
}
return true;
}
private Exchange getExchange(HttpServerExchange httpServerExchange) {
if (this.exchange == null) {
String authenticityToken = getRequestParameters(httpServerExchange).get(Default.AUTHENTICITY_TOKEN.toString());
if (StringUtils.isBlank(authenticityToken)) {
authenticityToken = this.form.get(Default.AUTHENTICITY_TOKEN.toString());
}
this.exchange = new Exchange(httpServerExchange, this.session, authenticityToken, this.authentication);
}
return this.exchange;
}
private boolean executeFilter(Annotation[] annotations, HttpServerExchange exchange) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
FilterWith filterWith = null;
boolean continueAfterFilter = true;
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(FilterWith.class)) {
filterWith = (FilterWith) annotation;
for (Class<?> clazz : filterWith.value()) {
if (continueAfterFilter) {
Method classMethod = clazz.getMethod(Default.FILTER_METHOD_NAME.toString(), Exchange.class);
continueAfterFilter = (boolean) classMethod.invoke(this.injector.getInstance(clazz), getExchange(exchange));
} else {
return false;
}
}
}
}
return continueAfterFilter;
}
private Response getResponse(HttpServerExchange exchange) throws IllegalAccessException, InvocationTargetException, IOException, TemplateException {
Response response;
if (this.parameters.isEmpty()) {
response = (Response) this.method.invoke(this.controller);
response.andTemplate(this.method.getName());
} else {
Object [] convertedParameters = getConvertedParameters(exchange);
response = (Response) this.method.invoke(this.controller, convertedParameters);
response.andTemplate(this.method.getName());
}
if (!response.isRendered()) {
if (response.getContent() != null && this.exchange != null && this.exchange.getContent() != null) {
response.getContent().putAll(this.exchange.getContent());
}
TemplateEngine templateEngine = this.injector.getInstance(TemplateEngine.class);
response.andBody(templateEngine.render(this.flash, this.session, this.form, this.injector.getInstance(Messages.class), this.controllerClass.getSimpleName(), response.getTemplate(), response.getContent()));
}
return response;
}
private Session getSession(HttpServerExchange exchange) {
Session requestSession = null;
Cookie cookie = exchange.getRequestCookies().get(this.config.getSessionCookieName());
if (cookie != null) {
String cookieValue = cookie.getValue();
if (StringUtils.isNotBlank(cookieValue)) {
if (this.config.getBoolean(Key.COOKIE_ENCRYPTION, false)) {
Crypto crypto = this.injector.getInstance(Crypto.class);
cookieValue = crypto.decrypt(cookieValue);
}
String sign = null;
String expires = null;
String authenticityToken = null;
String prefix = StringUtils.substringBefore(cookieValue, Default.DATA_DELIMITER.toString());
if (StringUtils.isNotBlank(prefix)) {
String [] prefixes = prefix.split("\\" + Default.DELIMITER.toString());
if (prefixes != null && prefixes.length == SESSION_PREFIX_LENGTH) {
sign = prefixes [INDEX_0];
authenticityToken = prefixes [INDEX_1];
expires = prefixes [INDEX_2];
}
}
if (StringUtils.isNotBlank(sign) && StringUtils.isNotBlank(expires) && StringUtils.isNotBlank(authenticityToken)) {
String data = cookieValue.substring(cookieValue.indexOf(Default.DATA_DELIMITER.toString()) + 1, cookieValue.length());
LocalDateTime expiresDate = LocalDateTime.parse(expires);
if (LocalDateTime.now().isBefore(expiresDate) && DigestUtils.sha512Hex(data + authenticityToken + expires + this.config.getApplicationSecret()).equals(sign)) {
Map<String, String> sessionValues = new HashMap<String, String>();
if (StringUtils.isNotEmpty(data)) {
for (Map.Entry<String, String> entry : Splitter.on(Default.SPLITTER.toString()).withKeyValueSeparator(Default.SEPERATOR.toString()).split(data).entrySet()) {
sessionValues.put(entry.getKey(), entry.getValue());
}
}
requestSession = new Session(sessionValues);
requestSession.setAuthenticityToken(authenticityToken);
requestSession.setExpires(expiresDate);
}
}
}
}
if (requestSession == null) {
requestSession = new Session();
requestSession.setAuthenticityToken(RandomStringUtils.randomAlphanumeric(TOKEN_LENGTH));
requestSession.setExpires(LocalDateTime.now().plusSeconds(this.config.getSessionExpires()));
}
this.session = requestSession;
return requestSession;
}
private void setSession(HttpServerExchange exchange) {
if (this.session != null && this.session.hasChanges()) {
String values = Joiner.on(Default.SPLITTER.toString()).withKeyValueSeparator(Default.SEPERATOR.toString()).join(this.session.getValues());
String sign = DigestUtils.sha512Hex(values + this.session.getAuthenticityToken() + this.session.getExpires() + config.getApplicationSecret());
String value = sign + Default.DELIMITER.toString() + this.session.getAuthenticityToken() + Default.DELIMITER.toString() + this.session.getExpires() + Default.DATA_DELIMITER.toString() + values;
if (this.config.getBoolean(Key.COOKIE_ENCRYPTION, false)) {
Crypto crypto = this.injector.getInstance(Crypto.class);
value = crypto.encrypt(value);
}
Cookie cookie = new CookieImpl(config.getString(Key.COOKIE_NAME), value)
.setHttpOnly(true)
.setPath("/")
.setExpires(Date.from(this.session.getExpires().atZone(ZoneId.systemDefault()).toInstant()));
exchange.setResponseCookie(cookie);
}
}
private Authentication getAuthentication(HttpServerExchange exchange) {
Authentication requestAuthentication = null;
Cookie cookie = exchange.getRequestCookies().get(this.config.getAuthenticationCookieName());
if (cookie != null) {
String cookieValue = cookie.getValue();
if (StringUtils.isNotBlank(cookieValue)) {
if (this.config.getBoolean(Key.AUTH_COOKIE_ENCRYPT.toString(), false)) {
Crypto crypto = this.injector.getInstance(Crypto.class);
cookieValue = crypto.decrypt(cookieValue);
}
String sign = null;
String expires = null;
String prefix = StringUtils.substringBefore(cookieValue, Default.DATA_DELIMITER.toString());
if (StringUtils.isNotBlank(prefix)) {
String [] prefixes = prefix.split("\\" + Default.DELIMITER.toString());
if (prefixes != null && prefixes.length == AUTH_PREFIX_LENGTH) {
sign = prefixes [INDEX_0];
expires = prefixes [INDEX_1];
}
}
if (StringUtils.isNotBlank(sign) && StringUtils.isNotBlank(expires)) {
String data = cookieValue.substring(cookieValue.indexOf(Default.DATA_DELIMITER.toString()) + 1, cookieValue.length());
LocalDateTime expiresDate = LocalDateTime.parse(expires);
if (LocalDateTime.now().isBefore(expiresDate) && DigestUtils.sha512Hex(data + expires + this.config.getApplicationSecret()).equals(sign)) {
requestAuthentication = new Authentication(this.config, data, expiresDate);
}
}
}
}
if (requestAuthentication == null) {
requestAuthentication = new Authentication(this.config);
requestAuthentication.setExpires(LocalDateTime.now().plusSeconds(this.config.getAuthenticationExpires()));
}
this.authentication = requestAuthentication;
return requestAuthentication;
}
private void setAuthentication(HttpServerExchange exchange) {
if (this.authentication != null && this.authentication.hasAuthenticatedUser()) {
Cookie cookie;
String cookieName = this.config.getAuthenticationCookieName();
if (this.authentication.isLogout()) {
cookie = exchange.getRequestCookies().get(cookieName);
cookie.setMaxAge(0);
cookie.setDiscard(true);
} else {
String sign = DigestUtils.sha512Hex(this.authentication.getAuthenticatedUser() + this.authentication.getExpires() + this.config.getString(Key.APPLICATION_SECRET));
String value = sign + Default.DELIMITER.toString() + this.authentication.getExpires() + Default.DATA_DELIMITER.toString() + this.authentication.getAuthenticatedUser();
if (this.config.getBoolean(Key.AUTH_COOKIE_ENCRYPT, false)) {
value = this.injector.getInstance(Crypto.class).encrypt(value);
}
cookie = new CookieImpl(cookieName, value)
.setHttpOnly(true)
.setPath("/")
.setExpires(Date.from(this.authentication.getExpires().atZone(ZoneId.systemDefault()).toInstant()));
}
exchange.setResponseCookie(cookie);
}
}
private void getFlash(HttpServerExchange exchange) {
Flash requestFlash = null;
Cookie cookie = exchange.getRequestCookies().get(this.config.getFlashCookieName());
if (cookie != null && StringUtils.isNotBlank(cookie.getValue())){
Map<String, String> values = new HashMap<String, String>();
for (Map.Entry<String, String> entry : Splitter.on("&").withKeyValueSeparator(":").split(cookie.getValue()).entrySet()) {
values.put(entry.getKey(), entry.getValue());
}
requestFlash = new Flash(values);
requestFlash.setDiscard(true);
}
if (requestFlash == null) {
requestFlash = new Flash();
}
this.flash = requestFlash;
}
private void setFlash(HttpServerExchange exchange) {
if (this.flash != null && !this.flash.isDiscard() && this.flash.hasContent()) {
String values = Joiner.on("&").withKeyValueSeparator(":").join(this.flash.getValues());
Cookie cookie = new CookieImpl(this.config.getFlashCookieName(), values)
.setHttpOnly(true)
.setPath("/");
exchange.setResponseCookie(cookie);
} else {
Cookie cookie = exchange.getRequestCookies().get(this.config.getFlashCookieName());
if (cookie != null) {
cookie.setHttpOnly(true)
.setPath("/")
.setMaxAge(0);
exchange.setResponseCookie(cookie);
}
}
}
private void getForm(HttpServerExchange exchange) throws IOException {
this.form = this.injector.getInstance(Form.class);
if (isPostOrPut(exchange)) {
final FormDataParser formDataParser = FormParserFactory.builder().build().createParser(exchange);
if (formDataParser != null) {
exchange.startBlocking();
FormData formData = formDataParser.parseBlocking();
for (String data : formData) {
for (FormData.FormValue formValue : formData.get(data)) {
if (formValue.isFile()) {
form.addFile(formValue.getFile());
} else {
form.add(new HttpString(data).toString(), formValue.getValue());
}
}
}
this.form.setSubmitted(true);
}
}
}
private Body getBody(HttpServerExchange exchange) throws IOException {
Body body = new Body();
if (isPostOrPut(exchange)) {
exchange.startBlocking();
body.setContent(IOUtils.toString(exchange.getInputStream()));
}
return body;
}
private boolean isPostOrPut(HttpServerExchange exchange) {
return (Methods.POST).equals(exchange.getRequestMethod()) || exchange.getRequestMethod().equals(Methods.PUT);
}
private Object[] getConvertedParameters(HttpServerExchange exchange) throws IOException {
Map<String, String> queryParameters = getRequestParameters(exchange);
Object [] convertedParameters = new Object[this.parameterCount];
int index = 0;
for (Map.Entry<String, Class<?>> entry : this.parameters.entrySet()) {
String key = entry.getKey();
Class<?> clazz = entry.getValue();
if ((Form.class).equals(clazz)) {
convertedParameters[index] = this.form;
} else if ((Authentication.class).equals(clazz)) {
convertedParameters[index] = this.authentication;
} else if ((Session.class).equals(clazz)) {
convertedParameters[index] = this.session;
} else if ((Flash.class).equals(clazz)) {
convertedParameters[index] = this.flash;
} else if ((Body.class).equals(clazz)) {
convertedParameters[index] = getBody(exchange);
} else if ((String.class).equals(clazz)) {
convertedParameters[index] = StringUtils.isBlank(queryParameters.get(key)) ? "" : queryParameters.get(key);
} else if ((Integer.class).equals(clazz) || (int.class).equals(clazz)) {
convertedParameters[index] = StringUtils.isBlank(queryParameters.get(key)) ? Integer.valueOf(0) : Integer.valueOf(queryParameters.get(key));
} else if ((Double.class).equals(clazz) || (double.class).equals(clazz)) {
convertedParameters[index] = StringUtils.isBlank(queryParameters.get(key)) ? Double.valueOf(0) : Double.valueOf(queryParameters.get(key));
} else if ((Float.class).equals(clazz) || (float.class).equals(clazz)) {
convertedParameters[index] = StringUtils.isBlank(queryParameters.get(key)) ? Float.valueOf(0) : Float.valueOf(queryParameters.get(key));
} else if ((Long.class).equals(clazz) || (long.class).equals(clazz)) {
convertedParameters[index] = StringUtils.isBlank(queryParameters.get(key)) ? Long.valueOf(0) : Long.valueOf(queryParameters.get(key));
} else if (exchange.getRequestHeaders() != null && exchange.getRequestHeaders().get(Headers.CONTENT_TYPE) != null &&
(ContentType.APPLICATION_JSON.toString()).equals(exchange.getRequestHeaders().get(Headers.CONTENT_TYPE).element())) {
convertedParameters[index] = this.mapper.readValue(getBody(exchange).asString(), clazz);
}
index++;
}
return convertedParameters;
}
private Map<String, String> getRequestParameters(HttpServerExchange exchange) {
Map<String, String> requestParamater = new HashMap<String, String>();
Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
queryParameters.putAll(exchange.getPathParameters());
for (Map.Entry<String, Deque<String>> entry : queryParameters.entrySet()) {
requestParamater.put(entry.getKey(), entry.getValue().element());
}
return requestParamater;
}
private Map<String, Class<?>> getMethodParameters() {
Map<String, Class<?>> methodParameters = new LinkedHashMap<String, Class<?>>();
for (Method declaredMethod : this.controller.getClass().getDeclaredMethods()) {
if (declaredMethod.getName().equals(this.controllerMethod) && declaredMethod.getParameterCount() > 0) {
Parameter[] declaredParameters = declaredMethod.getParameters();
for (Parameter parameter : declaredParameters) {
methodParameters.put(parameter.getName(), parameter.getType());
}
break;
}
}
return methodParameters;
}
}
|
package org.geotools.image;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.PackedColorModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.IIOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageOutputStreamSpi;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
import javax.media.jai.ColorCube;
import javax.media.jai.IHSColorSpace;
import javax.media.jai.ImageLayout;
import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.LookupTableJAI;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.ROI;
import javax.media.jai.RenderedOp;
import javax.media.jai.TileCache;
import javax.media.jai.operator.AddConstDescriptor;
import javax.media.jai.operator.AddDescriptor;
import javax.media.jai.operator.AndDescriptor;
import javax.media.jai.operator.BandCombineDescriptor;
import javax.media.jai.operator.BandMergeDescriptor;
import javax.media.jai.operator.BandSelectDescriptor;
import javax.media.jai.operator.BinarizeDescriptor;
import javax.media.jai.operator.ColorConvertDescriptor;
import javax.media.jai.operator.ErrorDiffusionDescriptor;
import javax.media.jai.operator.ExtremaDescriptor;
import javax.media.jai.operator.FormatDescriptor;
import javax.media.jai.operator.InvertDescriptor;
import javax.media.jai.operator.LookupDescriptor;
import javax.media.jai.operator.MultiplyConstDescriptor;
import javax.media.jai.operator.NotDescriptor;
import javax.media.jai.operator.NullDescriptor;
import javax.media.jai.operator.OrderedDitherDescriptor;
import javax.media.jai.operator.RescaleDescriptor;
import javax.media.jai.operator.XorConstDescriptor;
import org.geotools.factory.Hints;
import org.geotools.resources.Arguments;
import org.geotools.resources.i18n.ErrorKeys;
import org.geotools.resources.i18n.Errors;
import org.geotools.resources.image.ColorUtilities;
import org.geotools.resources.image.ImageUtilities;
import org.geotools.util.logging.Logging;
import com.sun.imageio.plugins.png.PNGImageWriter;
import com.sun.media.imageioimpl.common.BogusColorSpace;
import com.sun.media.imageioimpl.common.PackageUtil;
import com.sun.media.imageioimpl.plugins.gif.GIFImageWriter;
import com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi;
import com.sun.media.jai.util.ImageUtil;
/**
* Helper methods for applying JAI operations on an image. The image is specified at
* {@linkplain #ImageWorker(RenderedImage) creation time}. Sucessive operations can
* be applied by invoking the methods defined in this class, and the final image can
* be obtained by invoking {@link #getRenderedImage} at the end of the process.
* <p>
* If an exception is thrown during a method invocation, then this {@code ImageWorker}
* is left in an undetermined state and should not be used anymore.
*
* @since 2.3
* @source $URL$
* @version $Id$
* @author Simone Giannecchini
* @author Bryce Nordgren
* @author Martin Desruisseaux
*/
public class ImageWorker {
/**
* Workaround class for compressing PNG using the default
* {@link PNGImageEncoder} shipped with the JDK.
* <p>
* {@link PNGImageWriter} does not support
* {@link ImageWriteParam#setCompressionMode(int)} set to
* {@link ImageWriteParam#MODE_EXPLICIT}, it only allows
* {@link ImageWriteParam#MODE_DEFAULT}.
*
* @author Simone Giannecchini
*
* @todo Consider moving to {@link org.geotools.image.io} package.
*/
public final static class PNGImageWriteParam extends ImageWriteParam {
/**
* Default constructor.
*/
public PNGImageWriteParam() {
super();
this.canWriteProgressive = true;
this.canWriteCompressed = true;
this.locale = Locale.getDefault();
}
}
/**
* The logger to use for this class.
*/
private final static Logger LOGGER = Logging.getLogger("org.geotools.image");
/**
* If {@link Boolean#FALSE FALSE}, image operators are not allowed to
* produce tiled images. The default is {@link Boolean#TRUE TRUE}. The
* {@code FALSE} value is sometime useful for exporting images to some
* formats that doesn't support tiling (e.g. GIF).
*
* @see #setRenderingHint
*/
public static final Hints.Key TILING_ALLOWED = new Hints.Key(Boolean.class);
/**
* The image property name generated by {@link ExtremaDescriptor}.
*/
private static final String EXTREMA = "extrema";
/**
* The image specified by the user at construction time, or last time
* {@link #invalidateStatistics} were invoked. The {@link #getComputedProperty}
* method will not search a property pass this point.
*/
private RenderedImage inheritanceStopPoint;
/**
* The image being built.
*/
protected RenderedImage image;
/**
* The region of interest, or {@code null} if none.
*/
private ROI roi;
/**
* The rendering hints to provides to all image operators. Additional hints may
* be set (in a separated {@link RenderingHints} object) for particular images.
*/
private RenderingHints commonHints;
/**
* 0 if tile cache is enabled, any other value otherwise. This counter is
* incremented everytime {@code tileCacheEnabled(false)} is invoked, and
* decremented every time {@code tileCacheEnabled(true)} is invoked.
*/
private int tileCacheDisabled = 0;
/**
* Creates a new uninitialized builder for an {@linkplain #load image read}.
*
* @see #load
*/
public ImageWorker() {
inheritanceStopPoint = this.image = null;
}
/**
* Creates a new builder for an image read from the specified file.
*
* @param input The file to read.
* @throws IOException if the file can't be read.
*/
public ImageWorker(final File input) throws IOException {
this(ImageIO.read(input));
}
/**
* Creates a new builder for the specified image. The images to be computed (if any)
* will save their tiles in the default {@linkplain TileCache tile cache}.
*
* @param image The source image.
*/
public ImageWorker(final RenderedImage image) {
inheritanceStopPoint = this.image = image;
}
/**
* Prepare this builder for the specified image. The images to be computed (if any)
* will save their tiles in the default {@linkplain TileCache tile cache}.
*
* @param image The source image.
*/
public final ImageWorker setImage(final RenderedImage image) {
inheritanceStopPoint = this.image = image;
return this;
}
/**
* Creates a new image worker with the same hints but a different image.
*/
private ImageWorker fork(final RenderedImage image) {
final ImageWorker worker = new ImageWorker(image);
if (commonHints!=null && !commonHints.isEmpty()) {
RenderingHints hints = new RenderingHints(null);
hints.add(worker.commonHints);
worker.commonHints = hints;
}
return worker;
}
/**
* Loads an image using the provided file name and the
* {@linkplain #getRenderingHints current hints}, which are used to control caching and layout.
*
* @param source Filename of the source image to read.
* @param imageChoice Image index in multipage images.
* @param readMatadata If {@code true}, metadata will be read.
*/
public final void load(final String source, final int imageChoice, final boolean readMetadata) {
final ParameterBlockJAI pbj = new ParameterBlockJAI("ImageRead");
pbj.setParameter("Input", source)
.setParameter("ImageChoice", Integer.valueOf(imageChoice))
.setParameter("ReadMetadata", Boolean.valueOf(readMetadata))
.setParameter("VerifyInput", Boolean.TRUE);
image = JAI.create("ImageRead", pbj, getRenderingHints());
}
//////// IMAGE, PROPERTIES AND RENDERING HINTS ACCESSORS ////////
/**
* Returns the current image.
*
* @return The rendered image.
*
* @see #getBufferedImage
* @see #getPlanarImage
* @see #getRenderedOperation
* @see #getImageAsROI
*/
public final RenderedImage getRenderedImage() {
return image;
}
/**
* Returns the current image as a buffered image.
*
* @return The buffered image.
*
* @see #getRenderedImage
* @see #getPlanarImage
* @see #getRenderedOperation
* @see #getImageAsROI
*
* @since 2.5
*/
public final BufferedImage getBufferedImage() {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
} else {
return getPlanarImage().getAsBufferedImage();
}
}
/**
* Returns the {@linkplain #getRenderedImage rendered image} as a planar image.
*
* @return The planar image.
*
* @see #getRenderedImage
* @see #getRenderedOperation
* @see #getImageAsROI
*/
public final PlanarImage getPlanarImage() {
return PlanarImage.wrapRenderedImage(getRenderedImage());
}
/**
* Returns the {@linkplain #getRenderedImage rendered image} as a rendered operation.
*
* @return The rendered operation.
*
* @see #getRenderedImage
* @see #getPlanarImage
* @see #getImageAsROI
*/
public final RenderedOp getRenderedOperation() {
final RenderedImage image = getRenderedImage();
if (image instanceof RenderedOp) {
return (RenderedOp) image;
}
return NullDescriptor.create(image, getRenderingHints());
}
/**
* Returns a {@linkplain ROI Region Of Interest} built from the current
* {@linkplain #getRenderedImage image}. If the image is multi-bands, then this method first
* computes an estimation of its {@linkplain #intensity intensity}. Next, this method
* {@linkplain #binarize() binarize} the image and constructs a {@link ROI} from the result.
*
* @return The image as a region of interest.
*
* @see #getRenderedImage
* @see #getPlanarImage
* @see #getRenderedOperation
*/
public final ROI getImageAsROI() {
binarize();
return new ROI(getRenderedImage());
}
/**
* Returns the <cite>region of interest</cite> currently set, or {@code null} if none.
* The default value is {@code null}.
*
* @return The current region of interest.
*
* @see #getMinimums
* @see #getMaximums
*/
public final ROI getROI() {
return roi;
}
/**
* Set the <cite>region of interest</cite> (ROI). A {@code null} set the ROI to the whole
* {@linkplain #image}. The ROI is used by statistical methods like {@link #getMinimums}
* and {@link #getMaximums}.
*
* @param roi The new region of interest.
* @return This ImageWorker
*
* @see #getMinimums
* @see #getMaximums
*/
public final ImageWorker setROI(final ROI roi) {
this.roi = roi;
invalidateStatistics();
return this;
}
/**
* Returns the rendering hint for the specified key, or {@code null} if none.
*/
public final Object getRenderingHint(final RenderingHints.Key key) {
return (commonHints != null) ? commonHints.get(key) : null;
}
/**
* Sets a rendering hint tile to use for all images to be computed by this class. This method
* applies only to the next images to be computed; images already computed before this method
* call (if any) will not be affected.
* <p>
* Some common examples:
* <p>
* <ul>
* <li><code>setRenderingHint({@linkplain JAI#KEY_TILE_CACHE}, null)</code>
* disables completly the tile cache.</li>
* <li><code>setRenderingHint({@linkplain #TILING_ALLOWED}, Boolean.FALSE)</code>
* forces all operators to produce untiled images.</li>
* </ul>
*
* @return This ImageWorker
*/
public final ImageWorker setRenderingHint(final RenderingHints.Key key, final Object value) {
if (commonHints == null) {
commonHints = new RenderingHints(null);
}
commonHints.add(new RenderingHints(key,value));
return this;
}
/**
* Set a map of rendering hints to use for all images to be computed by this class. This method
* applies only to the next images to be computed; images already computed before this method
* call (if any) will not be affected.
*
* <p>
* If <code>hints</code> is null we won't modify this list.
* @return This ImageWorker
* @see #setRenderingHint(RenderingHints)
*/
public final ImageWorker setRenderingHints(final RenderingHints
hints) {
if (commonHints == null) {
commonHints = new RenderingHints(null);
}
if(hints!=null)
commonHints.add(hints);
return this;
}
/**
* Removes a rendering hint. Note that invoking this method is <strong>not</strong> the same
* than invoking <code>{@linkplain #setRenderingHint setRenderingHint}(key, null)</code>.
* This is especially true for the {@linkplain javax.media.jai.TileCache tile cache} hint:
* <p>
* <ul>
* <li><code>{@linkplain #setRenderingHint setRenderingHint}({@linkplain JAI#KEY_TILE_CACHE},
* null)</code> disables the use of any tile cache. In other words, this method call do
* request a tile cache, which happen to be the "null" cache.</li>
*
* <li><code>removeRenderingHint({@linkplain JAI#KEY_TILE_CACHE})</code> unsets any tile cache
* specified by a previous rendering hint. All images to be computed after this method
* call will save their tiles in the {@linkplain JAI#getTileCache JAI default tile
* cache}.</li>
* </ul>
*
* @return This ImageWorker
*/
public final ImageWorker removeRenderingHint(final RenderingHints.Key key) {
if (commonHints != null) {
commonHints.remove(key);
}
return this;
}
/**
* Returns the rendering hints for an image to be computed by this class.
* The default implementation returns the following hints:
* <p>
* <ul>
* <li>An {@linkplain ImageLayout image layout} with tiles size computed automatically
* from the current {@linkplain #image} size.</li>
* <li>Any additional hints specified through the {@link #setRenderingHint} method. If the
* user provided explicitly a {@link JAI#KEY_IMAGE_LAYOUT}, then the user layout has
* precedence over the automatic layout computed in previous step.</li>
* </ul>
*
* @return The rendering hints to use for image computation (never {@code null}).
*/
public final RenderingHints getRenderingHints() {
RenderingHints hints = ImageUtilities.getRenderingHints(image);
if (hints == null) {
hints = new RenderingHints(null);
if (commonHints != null) {
hints.add(commonHints);
}
} else if (commonHints != null) {
hints.putAll(commonHints);
}
if (Boolean.FALSE.equals(hints.get(TILING_ALLOWED))) {
final ImageLayout layout = getImageLayout(hints);
if (commonHints==null || layout != commonHints.get(JAI.KEY_IMAGE_LAYOUT)) {
// Set the layout only if it is not a user-supplied object.
layout.setTileWidth (image.getWidth());
layout.setTileHeight (image.getHeight());
layout.setTileGridXOffset(image.getMinX());
layout.setTileGridYOffset(image.getMinY());
hints.put(JAI.KEY_IMAGE_LAYOUT, layout);
}
}
if (tileCacheDisabled!=0 && (commonHints!=null &&!commonHints.containsKey(JAI.KEY_TILE_CACHE))) {
hints.add(new RenderingHints(JAI.KEY_TILE_CACHE, null));
}
return hints;
}
/**
* Returns the {@linkplain #getRenderingHints rendering hints}, but with a
* {@linkplain ComponentColorModel component color model} of the specified
* data type. The data type is changed only if no color model was explicitly
* specified by the user through {@link #getRenderingHints()}.
*
* @param type The data type (typically {@link DataBuffer#TYPE_BYTE}).
*/
private final RenderingHints getRenderingHints(final int type) {
/*
* Gets the default hints, which usually contains only informations about tiling.
* If the user overridden the rendering hints with an explict color model, keep
* the user's choice.
*/
final RenderingHints hints = getRenderingHints();
final ImageLayout layout = getImageLayout(hints);
if (layout.isValid(ImageLayout.COLOR_MODEL_MASK)) {
return hints;
}
/*
* Creates the new color model.
*/
final ColorModel oldCm = image.getColorModel();
if(oldCm!=null){
final ColorModel newCm= new ComponentColorModel(
oldCm.getColorSpace(),
oldCm.hasAlpha(), // If true, supports transparency.
oldCm.isAlphaPremultiplied(), // If true, alpha is premultiplied.
oldCm.getTransparency(), // What alpha values can be represented.
type); // Type of primitive array used to represent pixel.
/*
* Creating the final image layout which should allow us to change color model.
*/
layout.setColorModel(newCm);
layout.setSampleModel(newCm.createCompatibleSampleModel(image.getWidth(), image.getHeight()));
}else{
final int numBands=image.getSampleModel().getNumBands();
final ColorModel newCm= new ComponentColorModel(
new BogusColorSpace(numBands),
false, // If true, supports transparency.
false, // If true, alpha is premultiplied.
Transparency.OPAQUE, // What alpha values can be represented.
type); // Type of primitive array used to represent pixel.
/*
* Creating the final image layout which should allow us to change color model.
*/
layout.setColorModel(newCm);
layout.setSampleModel(newCm.createCompatibleSampleModel(image.getWidth(), image.getHeight()));
}
hints.put(JAI.KEY_IMAGE_LAYOUT, layout);
return hints;
}
/**
* Gets the image layout from the specified rendering hints, creating a new one if needed.
* This method do not modify the specified hints. If the caller modifies the image layout,
* it should invoke {@code hints.put(JAI.KEY_IMAGE_LAYOUT, layout)} explicitly.
*/
private static ImageLayout getImageLayout(final RenderingHints hints) {
final Object candidate = hints.get(JAI.KEY_IMAGE_LAYOUT);
if (candidate instanceof ImageLayout) {
return (ImageLayout) candidate;
}
return new ImageLayout();
}
/**
* If {@code false}, disables the tile cache. Invoking this method with value {@code true}
* cancel the last invocation with value {@code false}. If this method was invoking many
* time with value {@code false}, then this method must be invoked the same amount of time
* with the value {@code true} for reenabling the cache.
* <p>
* <strong>Note:</strong> This method name doesn't contain the usual {@code set} prefix
* because it doesn't really set a flag. Instead it increments or decrements a counter.
*
* @return This ImageWorker
*/
public final ImageWorker tileCacheEnabled(final boolean status) {
if (status) {
if (tileCacheDisabled != 0) {
tileCacheDisabled
} else {
throw new IllegalStateException();
}
} else {
tileCacheDisabled++;
}
return this;
}
/**
* Returns the number of bands in the {@linkplain #image}.
*
* @see #retainBands
* @see #retainFirstBand
* @see SampleModel#getNumBands
*/
public final int getNumBands() {
return image.getSampleModel().getNumBands();
}
/**
* Returns the transparent pixel value, or -1 if none.
*/
public final int getTransparentPixel() {
final ColorModel cm = image.getColorModel();
return (cm instanceof IndexColorModel) ? ((IndexColorModel) cm).getTransparentPixel() : -1;
}
/**
* Gets a property from the property set of the {@linkplain #image}. If the property name
* is not recognized, then {@link Image#UndefinedProperty} will be returned. This method
* do <strong>not</strong> inherits properties from the image specified at
* {@linkplain #ImageWorker(RenderedImage) construction time} - only properties generated
* by this class are returned.
*/
private Object getComputedProperty(final String name) {
final Object value = image.getProperty(name);
return (value == inheritanceStopPoint.getProperty(name)) ? Image.UndefinedProperty : value;
}
/**
* Returns the minimums and maximums values found in the image. Those extremas are
* returned as an array of the form {@code double[2][#bands]}.
*/
private double[][] getExtremas() {
Object extrema = getComputedProperty(EXTREMA);
if (!(extrema instanceof double[][])) {
final Integer ONE = 1;
image = ExtremaDescriptor.create(
image, // The source image.
roi, // The region of the image to scan. Default to all.
ONE, // The horizontal sampling rate. Default to 1.
ONE, // The vertical sampling rate. Default to 1.
null, // Whether to store extrema locations. Default to false.
ONE, // Maximum number of run length codes to store. Default to 1.
getRenderingHints());
extrema = getComputedProperty(EXTREMA);
}
return (double[][]) extrema;
}
/**
* Tells this builder that all statistics on pixel values (e.g. the "extrema" property
* in the {@linkplain #image}) should not be inherited from the source images (if any).
* This method should be invoked every time an operation changed the pixel values.
*
* @return This ImageWorker
*/
private ImageWorker invalidateStatistics() {
inheritanceStopPoint = image;
return this;
}
/**
* Returns the minimal values found in every {@linkplain #image} bands. If a
* {@linkplain #getROI region of interest} is defined, then the statistics
* will be computed only over that region.
*
* @see #getMaximums
* @see #setROI
*/
public final double[] getMinimums() {
return getExtremas()[0];
}
/**
* Returns the maximal values found in every {@linkplain #image} bands. If a
* {@linkplain #getROI region of interest} is defined, then the statistics
* will be computed only over that region.
*
* @see #getMinimums
* @see #setROI
*/
public final double[] getMaximums() {
return getExtremas()[1];
}
//////// KIND OF IMAGE (BYTES, BINARY, INDEXED, RGB...) ////////
/**
* Returns {@code true} if the {@linkplain #image} stores its pixel values in 8 bits.
*
* @see #rescaleToBytes
*/
public final boolean isBytes() {
final SampleModel sm = image.getSampleModel();
final int[] sampleSize=sm.getSampleSize();
for(int i=0;i<sampleSize.length;i++)
if(sampleSize[i]!=8)
return false;
return true;
}
/**
* Returns {@code true} if the {@linkplain #image} is binary. Such image usually contains
* only two values: 0 and 1.
*
* @see #binarize()
* @see #binarize(double)
* @see #binarize(int,int)
*/
public final boolean isBinary() {
return ImageUtil.isBinary(image.getSampleModel());
}
/**
* Returns {@code true} if the {@linkplain #image} uses an {@linkplain IndexColorModel
* index color model}.
*
* @see #forceIndexColorModel
* @see #forceBitmaskIndexColorModel
* @see #forceIndexColorModelForGIF
*/
public final boolean isIndexed() {
return image.getColorModel() instanceof IndexColorModel;
}
/**
* Returns {@code true} if the {@linkplain #image} uses a RGB {@linkplain ColorSpace color
* space}. Note that a RGB color space doesn't mean that pixel values are directly stored
* as RGB components. The image may be {@linkplain #isIndexed indexed} as well.
*
* @see #forceColorSpaceRGB
*/
public final boolean isColorSpaceRGB() {
final ColorModel cm = image.getColorModel();
if(cm==null)
return false;
return cm.getColorSpace().getType() == ColorSpace.TYPE_RGB;
}
/**
* Returns {@code true} if the {@linkplain #image} uses a GrayScale
* {@linkplain ColorSpace color space}. Note that a GrayScale color space
* doesn't mean that pixel values are directly stored as GrayScale
* component. The image may be {@linkplain #isIndexed indexed} as well.
*
* @see #forceColorSpaceGRAYScale
*/
public final boolean isColorSpaceGRAYScale() {
final ColorModel cm = image.getColorModel();
if(cm==null)
return false;
return cm.getColorSpace().getType() == ColorSpace.TYPE_GRAY;
}
/**
* Returns {@code true} if the {@linkplain #image} is
* {@linkplain Transparency#TRANSLUCENT translucent}.
*
* @see #forceBitmaskIndexColorModel
*/
public final boolean isTranslucent() {
return image.getColorModel().getTransparency() == Transparency.TRANSLUCENT;
}
//////// IMAGE OPERATORS ////////
/**
* Rescales the {@linkplain #image} such that it uses 8 bits. If the image already uses 8 bits,
* then this method does nothing. Otherwise this method computes the minimum and maximum values
* for each band, {@linkplain RescaleDescriptor rescale} them in the range {@code [0 .. 255]}
* and force the resulting image to {@link DataBuffer#TYPE_BYTE TYPE_BYTE}.
*
* @return This ImageWorker
*
* @see #isBytes
* @see RescaleDescriptor
*/
public final ImageWorker rescaleToBytes() {
if (isIndexed()) {
throw new UnsupportedOperationException(
"Rescaling not yet implemented for IndexColorModel.");
}
if (isBytes()) {
// Already using bytes - nothing to do.
return this;
}
final double[][] extrema = getExtremas();
final int length = extrema[0].length;
final double[] scale = new double[length];
final double[] offset = new double[length];
boolean computeRescale=false;
for (int i=0; i<length; i++) {
final double delta = extrema[1][i] - extrema[0][i];
if(Math.abs(delta)>1E-6 //maximum and minimum does not coincide
&&
((extrema[1][i]-255>1E-6) //the maximum is greater than 255
||
(extrema[0][i]<-1E-6))) //the minimum is smaller than 0
{
// we need to rescale
computeRescale=true;
// rescale factors
scale [i] = 255 / delta;
offset[i] = -scale[i] * extrema[0][i];
}
else
{
// we do not rescale explicitly bu in case we have to, we relay on the clamping capabilities of the format operator
scale [i] = 1;
offset[i] = 0;
}
}
final RenderingHints hints = getRenderingHints(DataBuffer.TYPE_BYTE);
if(computeRescale)
image = RescaleDescriptor.create(
image, // The source image.
scale, // The per-band constants to multiply by.
offset, // The per-band offsets to be added.
hints); // The rendering hints.
else
image= FormatDescriptor.create(
image, // The source image.
DataBuffer.TYPE_BYTE, // The destination image data type (BYTE)
hints); // The rendering hints.
invalidateStatistics(); // Extremas are no longer valid.
// All post conditions for this method contract.
assert isBytes();
return this;
}
/**
* Reduces the color model to {@linkplain IndexColorModel index color model}.
* If the current {@linkplain #image} already uses an
* {@linkplain IndexColorModel index color model}, then this method do
* nothing. Otherwise, the current implementation performs a ditering on the
* original color model. Note that this operation loose the alpha channel.
* <p>
* This for the moment should work only with opaque images, with non opaque
* images we just remove the alpha band in order to build an
* {@link IndexColorModel}. This is one because in general it could be very
* difficult to decide the final transparency for each pixel given the
* complexity if the algorithms for obtaining an {@link IndexColorModel}.
* <p>
* If an {@link IndexColorModel} with a single transparency index is enough
* for you, we advise you to take a look at
* {@link #forceIndexColorModelForGIF(boolean)} methdo.
*
* @see #isIndexed
* @see #forceBitmaskIndexColorModel
* @see #forceIndexColorModelForGIF
* @see OrderedDitherDescriptor
*/
public final ImageWorker forceIndexColorModel(final boolean error) {
final ColorModel cm = image.getColorModel();
if (cm instanceof IndexColorModel) {
// Already an index color model - nothing to do.
return this;
}
tileCacheEnabled(false);
if (getNumBands() % 2 == 0)
retainBands(getNumBands() - 1);
forceColorSpaceRGB();
final RenderingHints hints = getRenderingHints();
if (error) {
// color quantization
// final RenderedOp temp = ColorQuantizerDescriptor.create(image,
// ColorQuantizerDescriptor.MEDIANCUT, new Integer(254),
// new Integer(200), null, new Integer(1), new Integer(1),
// getRenderingHints());
// final ImageLayout layout= new ImageLayout();
// layout.setColorModel(temp.getColorModel());
// hints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT,layout));
// error diffusion
final KernelJAI ditherMask = KernelJAI.ERROR_FILTER_FLOYD_STEINBERG;
final LookupTableJAI colorMap = ColorCube.BYTE_496;
// (LookupTableJAI) temp.getProperty("JAI.LookupTable");
image = ErrorDiffusionDescriptor.create(image, colorMap,
ditherMask, hints);
} else {
// ordered dither
final KernelJAI[] ditherMask = KernelJAI.DITHER_MASK_443;
final ColorCube colorMap = ColorCube.BYTE_496;
image = OrderedDitherDescriptor.create(image, colorMap, ditherMask,
hints);
}
tileCacheEnabled(true);
invalidateStatistics();
// All post conditions for this method contract.
assert isIndexed();
return this;
}
/**
* Reduces the color model to {@linkplain IndexColorModel index color model}
* with {@linkplain Transparency#OPAQUE opaque} or
* {@linkplain Transparency#BITMASK bitmask} transparency. If the current
* {@linkplain #image} already uses a suitable color model, then this method
* do nothing.
*
* @return this {@link ImageWorker}.
*
* @see #isIndexed
* @see #isTranslucent
* @see #forceIndexColorModel
* @see #forceIndexColorModelForGIF
*/
public final ImageWorker forceBitmaskIndexColorModel() {
forceBitmaskIndexColorModel(getTransparentPixel(), true);
return this;
}
/**
* Reduces the color model to {@linkplain IndexColorModel index color model}
* with {@linkplain Transparency#OPAQUE opaque} or
* {@linkplain Transparency#BITMASK bitmask} transparency. If the current
* {@linkplain #image} already uses a suitable color model, then this method
* do nothing.
*
* @param suggestedTransparent
* A suggested pixel index to define as the transparent pixel. *
* @param errorDiffusion
* Tells if I should use {@link ErrorDiffusionDescriptor} or
* {@link OrderedDitherDescriptor} JAi operations. errorDiffusion
* @return this {@link ImageWorker}.
*
* @see #isIndexed
* @see #isTranslucent
* @see #forceIndexColorModel
* @see #forceIndexColorModelForGIF
*/
public final ImageWorker forceBitmaskIndexColorModel(int suggestedTransparent, final boolean errorDiffusion) {
final ColorModel cm = image.getColorModel();
if (cm instanceof IndexColorModel) {
final IndexColorModel oldCM = (IndexColorModel) cm;
switch (oldCM.getTransparency()) {
case Transparency.OPAQUE: {
// Suitable color model. There is nothing to do.
return this;
}
case Transparency.BITMASK: {
if (oldCM.getTransparentPixel() == suggestedTransparent) {
// Suitable color model. There is nothing to do.
return this;
}
break;
}
default: {
break;
}
}
// check if we already have a pixel fully transparent
final int transparentPixel = ColorUtilities.getTransparentPixel(oldCM);
/*
* The index color model need to be replaced. Creates a lookup table
* mapping from the old pixel values to new pixels values, with
* transparent colors mapped to the new transparent pixel value. The
* lookup table uses TYPE_BYTE or TYPE_USHORT, which are the two
* only types supported by IndexColorModel.
*/
final int mapSize = oldCM.getMapSize();
if(transparentPixel<0)
suggestedTransparent=suggestedTransparent<=mapSize?mapSize+1:suggestedTransparent;
else
suggestedTransparent=transparentPixel;
final int newSize = Math.max(mapSize, suggestedTransparent);
final int newPixelSize=ColorUtilities.getBitCount(newSize);
if(newPixelSize>16)
throw new IllegalArgumentException("Unable to create index color model with more than 65536 elements");
final LookupTableJAI lookupTable;
if (newPixelSize <= 8) {
final byte[] table = new byte[mapSize];
for (int i=0; i<mapSize; i++) {
table[i] = (byte) ((oldCM.getAlpha(i) == 0) ? suggestedTransparent : i);
}
lookupTable = new LookupTableJAI(table);
} else {
final short[] table = new short[mapSize];
for (int i=0; i<mapSize; i++) {
table[i] = (short) ((oldCM.getAlpha(i) == 0) ? suggestedTransparent : i);
}
lookupTable = new LookupTableJAI(table, true);
}
/*
* Now we need to perform the look up transformation. First of all
* we create the new color model with a bitmask transparency using
* the transparency index specified to this method. Then we perform
* the lookup operation in order to prepare for the gif image.
*/
final byte[][] rgb = new byte[3][newSize];
oldCM.getReds (rgb[0]);
oldCM.getGreens(rgb[1]);
oldCM.getBlues (rgb[2]);
final IndexColorModel newCM = new IndexColorModel(newPixelSize,newSize, rgb[0], rgb[1], rgb[2], suggestedTransparent);
final RenderingHints hints = getRenderingHints();
final ImageLayout layout = getImageLayout(hints);
layout.setColorModel(newCM);
// we should not transform on color map here
hints.put(JAI.KEY_TRANSFORM_ON_COLORMAP,Boolean.FALSE);
hints.put(JAI.KEY_IMAGE_LAYOUT, layout);
image = LookupDescriptor.create(image, lookupTable, hints);
//workaround bug in Lookup since it looks like it is switching 255 and 254
image=FormatDescriptor.create(image, image.getSampleModel().getDataType(), hints);
} else {
// force component color model first
forceComponentColorModel(true);
/*
* The image is not indexed.
*/
if (cm.hasAlpha()) {
//Getting the alpha channel.
tileCacheEnabled(false);
int numBands = getNumBands();
final RenderingHints hints = getRenderingHints();
final RenderedOp alphaChannel = BandSelectDescriptor.create(image,
new int[] { --numBands }, hints);
retainBands(numBands);
forceIndexColorModel(errorDiffusion);
tileCacheEnabled(true);
/*
* Adding transparency if needed, which means using the alpha
* channel to build a new color model. The method call below implies
* 'forceColorSpaceRGB()' and 'forceIndexColorModel()' method calls.
*/
addTransparencyToIndexColorModel(alphaChannel, false, suggestedTransparent, errorDiffusion);
}
else
forceIndexColorModel(errorDiffusion);
}
// All post conditions for this method contract.
assert isIndexed();
assert !isTranslucent();
return this;
}
/**
* Converts the image to a GIF-compliant image. This method has been created
* in order to convert the input image to a form that is compatible with the
* GIF model. It first remove the information about transparency since the
* error diffusion and the error dither operations are unable to process
* images with more than 3 bands. Afterwards the image is processed with an
* error diffusion operator in order to reduce the number of bands from 3 to
* 1 and the number of color to 216. A suitable layout is used for the final
* image via the {@linkplain #getRenderingHints rendering hints} in order to
* take into account the different layout model for the final image.
* <p>
* <strong>Tip:</strong> For optimizing writing GIF, we need to create the
* image untiled. This can be done by invoking
* <code>{@linkplain #setRenderingHint setRenderingHint}({@linkplain
* #TILING_ALLOWED}, Boolean.FALSE)</code>
* first.
*
* @param errorDiffusion
* Tells if I should use {@link ErrorDiffusionDescriptor} or
* {@link OrderedDitherDescriptor} JAi operations.
*
* @return this {@link ImageWorker}.
*
* @see #isIndexed
* @see #forceIndexColorModel
* @see #forceBitmaskIndexColorModel
*/
public final ImageWorker forceIndexColorModelForGIF(final boolean errorDiffusion) {
/*
* Checking the color model to see if we need to convert it back to
* color model. We might also need to reformat the image in order to get
* it to 8 bits samples.
*/
ColorModel cm= image.getColorModel();
if (cm instanceof PackedColorModel) {
forceComponentColorModel();
cm= image.getColorModel();
}
if(!(cm instanceof IndexColorModel))
rescaleToBytes();
/*
* Getting the alpha channel and separating from the others bands. If
* the initial image had no alpha channel (more specifically, if it is
* either opaque or a bitmask) we proceed without doing anything since
* it seems that GIF encoder in such a case works fine. If we need to
* create a bitmask, we will use the last index value allowed (255) as
* the transparent pixel value.
*/
if (isTranslucent()) {
forceBitmaskIndexColorModel(255, errorDiffusion);
} else {
forceIndexColorModel(errorDiffusion);
}
// All post conditions for this method contract.
assert isBytes();
assert isIndexed();
assert !isTranslucent();
return this;
}
/**
* Reformats the {@linkplain ColorModel color model} to a
* {@linkplain ComponentColorModel component color model} preserving
* transparency. This is used especially in order to go from
* {@link PackedColorModel} to {@link ComponentColorModel}, which seems to
* be well accepted from {@code PNGEncoder} and {@code TIFFEncoder}.
* <p>
* This code is adapted from jai-interests mailing list archive.
*
* @return this {@link ImageWorker}.
*
* @see FormatDescriptor
*/
public final ImageWorker forceComponentColorModel() {
return forceComponentColorModel(false);
}
/**
* Reformats the {@linkplain ColorModel color model} to a
* {@linkplain ComponentColorModel component color model} preserving
* transparency. This is used especially in order to go from
* {@link PackedColorModel} to {@link ComponentColorModel}, which seems to
* be well accepted from {@code PNGEncoder} and {@code TIFFEncoder}.
* <p>
* This code is adapted from jai-interests mailing list archive.
*
* @param checkTransparent
* @param optimizeGray
*
* @return this {@link ImageWorker}.
*
* @see FormatDescriptor
*/
public final ImageWorker forceComponentColorModel(boolean checkTransparent,boolean optimizeGray) {
final ColorModel cm = image.getColorModel();
if (cm instanceof ComponentColorModel) {
// Already an component color model - nothing to do.
return this;
}
// shortcut for index color model
if (cm instanceof IndexColorModel) {
final IndexColorModel icm = (IndexColorModel) cm;
final SampleModel sm = this.image.getSampleModel();
final int datatype = sm.getDataType();
final boolean gray = ColorUtilities.isGrayPalette(icm, checkTransparent)&optimizeGray;
final boolean alpha = icm.hasAlpha();
/*
* If the image is grayscale, retain only the needed bands.
*
*/
final int numDestinationBands = gray?(alpha?2:1):(alpha?4:3);
LookupTableJAI lut = null;
switch (datatype) {
case DataBuffer.TYPE_BYTE:
{
final byte data[][] = new byte[numDestinationBands][icm.getMapSize()];
icm.getReds (data[0]);
if(numDestinationBands>=2)
// remember to optimize for grayscale images
if(!gray)
icm.getGreens(data[1]);
else
icm.getAlphas(data[1]);
if(numDestinationBands>=3)
icm.getBlues (data[2]);
if (numDestinationBands == 4) {
icm.getAlphas(data[3]);
}
lut = new LookupTableJAI(data);
}
break;
case DataBuffer.TYPE_USHORT:
{
final int mapSize=icm.getMapSize();
final short data[][] = new short[numDestinationBands][mapSize];
for(int i=0;i<mapSize;i++)
{
data[0][i]=(short) icm.getRed(i);
if(numDestinationBands>=2)
// remember to optimize for grayscale images
if(!gray)
data[1][i]=(short)icm.getGreen(i);
else
data[1][i]=(short)icm.getAlpha(i);
if(numDestinationBands>=3)
data[2][i]=(short)icm.getBlue(i);
if (numDestinationBands == 4) {
data[3][i]=(short)icm.getAlpha(i);
}
}
lut = new LookupTableJAI(data,datatype==DataBuffer.TYPE_USHORT);
}
break;
default:
throw new IllegalArgumentException(
Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2,"datatype", datatype));
}
//did we initialized the LUT?
if(lut==null)
throw new IllegalStateException(
Errors.format(ErrorKeys.NULL_ARGUMENT_$1,"lut"));
/*
* Get the default hints, which usually contains only informations
* about tiling. If the user override the rendering hints with an
* explicit color model, keep the user's choice.
*/
final RenderingHints hints = (RenderingHints) getRenderingHints();
final ImageLayout layout;
final Object candidate = hints.get(JAI.KEY_IMAGE_LAYOUT);
if (candidate instanceof ImageLayout) {
layout= (ImageLayout) candidate;
}
else
{
layout= new ImageLayout(image);
hints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT,layout));
}
int[] bits= new int[numDestinationBands];
//bits per component
for(int i=0;i<numDestinationBands;i++)
bits[i]=sm.getSampleSize(i);
final ComponentColorModel destinationColorModel=new ComponentColorModel(
numDestinationBands>=3?ColorSpace.getInstance(ColorSpace.CS_sRGB):ColorSpace.getInstance(ColorSpace.CS_GRAY),
bits,
alpha,
cm.isAlphaPremultiplied(),
alpha?Transparency.TRANSLUCENT:Transparency.OPAQUE,
datatype);
final SampleModel destinationSampleModel=destinationColorModel.createCompatibleSampleModel(image.getWidth(), image.getHeight());
layout.setColorModel(destinationColorModel);
layout.setSampleModel(destinationSampleModel);
image = LookupDescriptor.create(image, lut, hints);
} else {
// Most of the code adapted from jai-interests is in 'getRenderingHints(int)'.
final int type = (cm instanceof DirectColorModel) ?DataBuffer.TYPE_BYTE : image.getSampleModel().getTransferType();
final RenderingHints hints = getRenderingHints(type);
// image=ColorConvertDescriptor.create(image, RIFUtil.getImageLayoutHint(hints).getColorModel(null), hints);
image = FormatDescriptor.create(image, type, hints);;
}
invalidateStatistics();
// All post conditions for this method contract.
assert image.getColorModel() instanceof ComponentColorModel;
return this;
}
/**
* Reformats the {@linkplain ColorModel color model} to a
* {@linkplain ComponentColorModel component color model} preserving
* transparency. This is used especially in order to go from
* {@link PackedColorModel} to {@link ComponentColorModel}, which seems to
* be well accepted from {@code PNGEncoder} and {@code TIFFEncoder}.
* <p>
* This code is adapted from jai-interests mailing list archive.
*
* @param checkTransparent
* tells this method to not consider fully transparent pixels
* when optimizing grayscale palettes.
*
* @return this {@link ImageWorker}.
*
* @see FormatDescriptor
*/
public final ImageWorker forceComponentColorModel(boolean checkTransparent) {
return forceComponentColorModel(checkTransparent,true);
}
/**
* Forces the {@linkplain #image} color model to the
* {@linkplain ColorSpace#CS_sRGB RGB color space}. If the current color
* space is already of {@linkplain ColorSpace#TYPE_RGB RGB type}, then this
* method does nothing. This operation may loose the alpha channel.
*
* @return this {@link ImageWorker}.
*
* @see #isColorSpaceRGB
* @see ColorConvertDescriptor
*/
public final ImageWorker forceColorSpaceRGB() {
if (!isColorSpaceRGB()) {
final ColorModel cm = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false,
Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
image = ColorConvertDescriptor.create(image, cm, getRenderingHints());
invalidateStatistics();
}
// All post conditions for this method contract.
assert isColorSpaceRGB();
return this;
}
/**
* Forces the {@linkplain #image} color model to the
* IHS color space. If the current color
* space is already of IHS type, then this
* method does nothing. This operation may loose the alpha channel.
*
* @return this {@link ImageWorker}.
*
* @see ColorConvertDescriptor
*/
public final ImageWorker forceColorSpaceIHS() {
if (!(image.getColorModel().getColorSpace() instanceof IHSColorSpace)) {
forceComponentColorModel();
// Create a ColorModel to convert the image to IHS.
final IHSColorSpace ihs = IHSColorSpace.getInstance();
final int numBits=image.getColorModel().getComponentSize(0);
final ColorModel ihsColorModel = new ComponentColorModel(ihs, new int[] {
numBits, numBits, numBits }, false, false, Transparency.OPAQUE,
image.getSampleModel().getDataType());
// Create a ParameterBlock for the conversion.
final ParameterBlock pb = new ParameterBlock();
pb.addSource(image);
pb.add(ihsColorModel);
// Do the conversion.
image = JAI.create("colorconvert", pb);
invalidateStatistics();
}
// All post conditions for this method contract.
assert image.getColorModel().getColorSpace() instanceof IHSColorSpace;
return this;
}
/**
* Add the bands to the Component Color Model
*
* @param writeband
* number of bands after the bandmerge.
*
* @return this {@link ImageWorker}.
*
*/
public final ImageWorker bandMerge(int writeband) {
ParameterBlock pb = new ParameterBlock();
PlanarImage sourceImage = PlanarImage
.wrapRenderedImage(getRenderedImage());
int numBands = sourceImage.getSampleModel().getNumBands();
// getting first band
final RenderedImage firstBand = JAI.create("bandSelect", sourceImage,
new int[] { 0 });
// adding to the image
final int length=writeband-numBands;
for (int i = 0; i < length; i++) {
pb.removeParameters();
pb.removeSources();
pb.addSource(sourceImage);
pb.addSource(firstBand);
sourceImage = JAI.create("bandmerge", pb);
pb.removeParameters();
pb.removeSources();
}
image = (RenderedImage) sourceImage;
invalidateStatistics();
// All post conditions for this method contract.
assert image.getSampleModel().getNumBands() == writeband;
return this;
}
/**
* Perform a BandMerge operation between the underlying image and the provided one.
*
* @param image
* to merge with the underlying one.
* @param before <code>true</code> if we want to use first the provided image, <code>false</code>
* otherwise.
*
* @return this {@link ImageWorker}.
*
*/
public final ImageWorker addBand(RenderedImage image, boolean before) {
this.image = before?
BandMergeDescriptor.create(image, this.image, this.getRenderingHints()):
BandMergeDescriptor.create(this.image, image, this.getRenderingHints());
invalidateStatistics();
return this;
}
/**
* Forces the {@linkplain #image} color model to the
* {@linkplain ColorSpace#CS_GRAY GRAYScale color space}. If the current
* color space is already of {@linkplain ColorSpace#TYPE_GRAY type}, then
* this method does nothing.
*
* @return this {@link ImageWorker}.
*
* @see #isColorSpaceGRAYScale
* @see ColorConvertDescriptor
*/
public final ImageWorker forceColorSpaceGRAYScale() {
if (!isColorSpaceRGB()) {
final ColorModel cm = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
image = ColorConvertDescriptor.create(image, cm, getRenderingHints());
invalidateStatistics();
}
// All post conditions for this method contract.
assert isColorSpaceGRAYScale();
return this;
}
/**
* Creates an image which represents approximatively the intensity of
* {@linkplain #image}. The result is always a single-banded image. If the
* image uses an {@linkplain IHSColorSpace IHS color space}, then this
* method just {@linkplain #retainFirstBand retain the first band} without
* any further processing. Otherwise, this method performs a simple
* {@linkplain BandCombineDescriptor band combine} operation on the
* {@linkplain #image} in order to come up with a simple estimation of the
* intensity of the image based on the average value of the color
* components. It is worthwhile to note that the alpha band is stripped from
* the image.
*
* @return this {@link ImageWorker}.
*
* @see BandCombineDescriptor
*/
public final ImageWorker intensity() {
/*
* If the color model already uses a IHS color space or a Gray color
* space, keep only the intensity band. Otherwise, we need a component
* color model to be sure to understand what we are doing.
*/
ColorModel cm = image.getColorModel();
final ColorSpace cs = cm.getColorSpace();
if (cs.getType() == ColorSpace.TYPE_GRAY || cs instanceof IHSColorSpace) {
retainFirstBand();
return this;
}
if (cm instanceof IndexColorModel) {
forceComponentColorModel();
cm = image.getColorModel();
}
// Number of color componenents
final int numBands = cm.getNumComponents();
final int numColorBands = cm.getNumColorComponents();
final boolean hasAlpha = cm.hasAlpha();
// One band, nothing to combine.
if (numBands == 1) {
return this;
}
// One band plus alpha, let's remove alpha.
if (numColorBands == 1 && hasAlpha) {
retainFirstBand();
return this;
}
//remove the alpha band
if (numColorBands != numBands) {
this.retainBands(numBands);
}
/*
* We have more than one band. Note that there is no need to remove the
* alpha band before to apply the "bandCombine" operation - it is
* suffisient to let the coefficient for the alpha band to the 0 value.
*/
final double[][] coeff = new double[1][numBands + 1];
Arrays.fill(coeff[0], 0, numColorBands, 1.0 / numColorBands);
image = BandCombineDescriptor.create(image, coeff, getRenderingHints());
invalidateStatistics();
// All post conditions for this method contract.
assert getNumBands() == 1;
return this;
}
/**
* Retains inconditionnaly the first band of {@linkplain #image}. All other
* bands (if any) are discarted without any further processing.
*
* @return this {@link ImageWorker}.
*
* @see #getNumBands
* @see #retainBands
* @see BandSelectDescriptor
*/
public final ImageWorker retainFirstBand() {
retainBands(1);
// All post conditions for this method contract.
assert getNumBands() == 1;
return this;
}
/**
* Retains inconditionnaly the last band of {@linkplain #image}. All other
* bands (if any) are discarted without any further processing.
*
* @return this {@link ImageWorker}.
*
* @see #getNumBands
* @see #retainBands
* @see BandSelectDescriptor
*/
public final ImageWorker retainLastBand() {
final int band = getNumBands() - 1;
if (band != 0) {
retainBands(new int[] {band});
}
// All post conditions for this method contract.
assert getNumBands() == 1;
return this;
}
/**
* Retains inconditionnaly the first {@code numBands} of {@linkplain #image}.
* All other bands (if any) are discarted without any further processing.
* This method does nothing if the current {@linkplain #image} does not have
* a greater amount of bands than {@code numBands}.
*
* @param numBands
* the number of bands to retain.
* @return this {@link ImageWorker}.
*
* @see #getNumBands
* @see #retainFirstBand
* @see BandSelectDescriptor
*/
public final ImageWorker retainBands(final int numBands) {
if (numBands <= 0) {
throw new IndexOutOfBoundsException(Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2,
"numBands", numBands));
}
if (getNumBands() > numBands) {
final int[] bands = new int[numBands];
for (int i=0; i<bands.length; i++) {
bands[i] = i;
}
image = BandSelectDescriptor.create(image, bands, getRenderingHints());
}
// All post conditions for this method contract.
assert getNumBands() <= numBands;
return this;
}
/**
* Retains inconditionnaly certain bands of {@linkplain #image}. All other
* bands (if any) are discarded without any further processing.
*
* @param bands
* the bands to retain.
* @return this {@link ImageWorker}.
*
* @see #getNumBands
* @see #retainFirstBand
* @see BandSelectDescriptor
*/
public final ImageWorker retainBands(final int[] bands) {
image = BandSelectDescriptor.create(image, bands, getRenderingHints());
return this;
}
/**
* Formats the underlying image to the provided data type.
*
* @param dataType
* to be used for this {@link FormatDescriptor} operation.
* @return this {@link ImageWorker}
*/
public final ImageWorker format(final int dataType) {
image = FormatDescriptor.create(image, dataType, getRenderingHints());
// All post conditions for this method contract.
assert image.getSampleModel().getDataType() == dataType;
return this;
}
/**
* Binarizes the {@linkplain #image}. If the image is multi-bands, then
* this method first computes an estimation of its
* {@linkplain #intensity intensity}. Then, the threshold value is set
* halfway between the minimal and maximal values found in the image.
*
* @return this {@link ImageWorker}.
*
* @see #isBinary
* @see #binarize(double)
* @see #binarize(int,int)
* @see BinarizeDescriptor
*/
public final ImageWorker binarize() {
binarize(Double.NaN);
// All post conditions for this method contract.
assert isBinary();
return this;
}
/**
* Binarizes the {@linkplain #image}. If the image is already binarized,
* then this method does nothing.
*
* @param threshold
* The threshold value.
* @return this {@link ImageWorker}.
*
* @see #isBinary
* @see #binarize()
* @see #binarize(int,int)
* @see BinarizeDescriptor
*/
public final ImageWorker binarize(double threshold) {
// If the image is already binary and the threshold is >=1 then there is no work to do.
if (!isBinary()) {
if (Double.isNaN(threshold)) {
if (getNumBands() != 1) {
tileCacheEnabled(false);
intensity();
tileCacheEnabled(true);
}
final double[][] extremas = getExtremas();
threshold = 0.5 * (extremas[0][0] + extremas[1][0]);
}
final RenderingHints hints = getRenderingHints();
image = BinarizeDescriptor.create(image, threshold, hints);
invalidateStatistics();
}
// All post conditions for this method contract.
assert isBinary();
return this;
}
/**
* Binarizes the {@linkplain #image} (if not already done) and replace all 0
* values by {@code value0} and all 1 values by {@code value1}. If the
* image should be binarized using a custom threshold value (instead of the
* automatic one), invoke {@link #binarize(double)} explicitly before this
* method.
*
* @return this {@link ImageWorker}.
* @see #isBinary
* @see #binarize()
* @see #binarize(double)
* @see BinarizeDescriptor
* @see LookupDescriptor
*/
public final ImageWorker binarize(final int value0, final int value1) {
tileCacheEnabled(false);
binarize();
tileCacheEnabled(true);
final LookupTableJAI table;
final int min = Math.min(value0, value1);
if (min >= 0) {
final int max = Math.max(value0, value1);
if (max < 256) {
table = new LookupTableJAI(new byte[] {(byte) value0, (byte) value1});
} else if (max < 65536) {
table = new LookupTableJAI(new short[] {(short) value0, (short) value1}, true);
} else {
table = new LookupTableJAI(new int[] {value0, value1});
}
} else {
table = new LookupTableJAI(new int[] { value0, value1 });
}
image = LookupDescriptor.create(image, table, getRenderingHints());
invalidateStatistics();
return this;
}
public final ImageWorker makeColorTransparent(final Color transparentColor)
throws IllegalStateException
{
if (transparentColor == null) {
throw new IllegalArgumentException(
Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "transparentColor"));
}
final ColorModel cm = image.getColorModel();
if (cm instanceof IndexColorModel) {
return maskIndexColorModel(transparentColor);
} else if (cm instanceof ComponentColorModel) {
switch (image.getSampleModel().getDataType()) {
case DataBuffer.TYPE_BYTE: {
return maskComponentColorModelByte(transparentColor);
}
// Add other types here if we support them...
}
}
throw new IllegalStateException(Errors.format(ErrorKeys.UNSUPPORTED_DATA_TYPE));
}
/**
* For an image backed by an {@link IndexColorModel}, replaces all occurences of the given
* color (usually opaque) by a fully transparent color.
*
* @param transparentColor The color to make transparent.
* @return this image worker.
*
*/
private final ImageWorker maskIndexColorModel(final Color transparentColor) {
assert image.getColorModel() instanceof IndexColorModel;
// Gets informations about the provided images.
IndexColorModel cm = (IndexColorModel) image.getColorModel();
final int numComponents = cm.getNumComponents();
int transparency = cm.getTransparency();
int transparencyIndex = cm.getTransparentPixel();
final int mapSize = cm.getMapSize();
final int transparentRGB = transparentColor.getRGB() & 0x00FFFFFF;
/*
* Optimization in case of Transparency.BITMASK.
* If the color we want to use as the fully transparent one is the same
* that is actually used as the transparent color, we leave doing nothing.
*/
if (transparency == Transparency.BITMASK && transparencyIndex != -1) {
int transpColor = cm.getRGB(transparencyIndex) & 0x00FFFFFF;
if (transpColor == transparentRGB) {
return this;
}
}
/*
* Find the index of the specified color. Most of the time, the color should appears only
* once, which will leads us to a BITMASK image. However we allows more occurences, which
* will leads us to a TRANSLUCENT image.
*/
final List<Integer> transparentPixelsIndexes = new ArrayList<Integer>();
for (int i=0; i<mapSize; i++) {
// Gets the color for this pixel removing the alpha information.
final int color = cm.getRGB(i) & 0xFFFFFF;
if (transparentRGB == color) {
transparentPixelsIndexes.add(i);
if (Transparency.BITMASK == transparency) {
break;
}
}
}
final int found = transparentPixelsIndexes.size();
if (found == 1) {
// Transparent color found.
transparencyIndex = transparentPixelsIndexes.get(0);
transparency = Transparency.BITMASK;
} else if (found == 0) {
return this;
} else {
transparencyIndex = -1;
transparency = Transparency.TRANSLUCENT;
}
// Prepare the new ColorModel.
// Get the old map and update it as needed.
final byte rgb[][] = new byte[4][mapSize];
cm.getReds (rgb[0]);
cm.getGreens(rgb[1]);
cm.getBlues (rgb[2]);
if (numComponents == 4) {
cm.getAlphas(rgb[3]);
} else {
Arrays.fill(rgb[3], (byte) 255);
}
if (transparency != Transparency.TRANSLUCENT) {
cm = new IndexColorModel(cm.getPixelSize(), mapSize,
rgb[0], rgb[1], rgb[2], transparencyIndex);
} else {
for (int k=0; k<found; k++) {
rgb[3][transparentPixelsIndexes.get(k)] = (byte) 0;
}
cm = new IndexColorModel(cm.getPixelSize(), mapSize,
rgb[0], rgb[1], rgb[2], rgb[3]);
}
// Format the input image.
final ImageLayout layout = new ImageLayout(image);
layout.setColorModel(cm);
final RenderingHints hints = getRenderingHints();
hints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.FALSE));
image = FormatDescriptor.create(image, image.getSampleModel().getDataType(), hints);
invalidateStatistics();
return this;
}
/**
* For an image backed by an {@link ComponentColorModel}, replaces all occurences
* of the given color (usually opaque) by a fully transparent color.
*
* @param transparentColor The color to make transparent.
* @return this image worker.
*
*
* Current implementation invokes a lot of JAI operations:
*
* "BandSelect" --> "Lookup" --> "BandCombine" --> "Extrema" --> "Binarize" -->
* "Format" --> "BandSelect" (one more time) --> "Multiply" --> "BandMerge".
*
* I would expect more speed and memory efficiency by writing our own JAI operation (PointOp
* subclass) doing that in one step. It would also be more deterministic (our "binarize" method
* depends on statistics on pixel values) and avoid unwanted side-effect like turning black
* color (RGB = 0,0,0) to transparent one. It would also be easier to maintain I believe.
*/
private final ImageWorker maskComponentColorModelByte(final Color transparentColor) {
assert image.getColorModel() instanceof ComponentColorModel;
assert image.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE;
/*
* Prepares the look up table for the source image.
* Remember what follows which is taken from the JAI programming guide.
*
* "The lookup operation performs a general table lookup on a rendered or renderable
* image. The destination image is obtained by passing the source image through the
* lookup table. The source image may be single- or multi-banded of data types byte,
* ushort, short, or int. The lookup table may be single- or multi-banded of any JAI-
* supported data types.
*
* The destination image must have the same data type as the lookup table, and its
* number of bands is determined based on the number of bands of the source and the
* table. If the source is single-banded, the destination has the same number of bands
* as the lookup table; otherwise, the destination has the same number of bands as the
* source.
*
* If either the source or the table is single-banded and the other one is multibanded,
* the single band is applied to every band of the multi-banded object. If both are
* multi-banded, their corresponding bands are matched up."
*
* A final annotation, if we have an input image with transparency we just DROP it since
* we want to re-add it using the supplied color as the mask for transparency.
*/
/*
* In case of a gray color model we can do everything in one step by expanding
* the color model to get one more band directly which is the alpha band itself.
*
* For a multiband image the lookup is applied to each band separately.
* This means that we cannot control directly the image as a whole but
* we need first to interact with the single bands then to combine the
* result into a single band that will provide us with the alpha band.
*/
int numBands = image.getSampleModel().getNumBands();
final int numColorBands = image.getColorModel().getNumColorComponents();
final RenderingHints hints = getRenderingHints();
if (numColorBands != numBands) {
// Typically, numColorBands will be equals to numBands-1.
final int[] opaqueBands = new int[numColorBands];
for (int i=0; i<opaqueBands.length; i++) {
opaqueBands[i] = i;
}
image = BandSelectDescriptor.create(image, opaqueBands, hints);
numBands=numColorBands;
}
// now prepare the lookups
final byte[][] tableData = new byte[numColorBands][256];
final boolean singleStep = (numColorBands == 1);
if (singleStep) {
final byte[] data = tableData[0];
Arrays.fill(data, (byte) 255);
data[transparentColor.getRed()] = 0;
} else {
switch (numColorBands) {
case 3:
Arrays.fill(tableData[2], (byte) 255);
tableData[2][transparentColor.getBlue() ] = 0; // fall through
case 2:
Arrays.fill(tableData[1], (byte) 255);
tableData[1][transparentColor.getGreen()] = 0; // fall through
case 1:
Arrays.fill(tableData[0], (byte) 255);
tableData[0][transparentColor.getRed() ] = 0; // fall through
case 0: break;
}
}
// Create a LookupTableJAI object to be used with the "lookup" operator.
LookupTableJAI table = new LookupTableJAI(tableData);
// Do the lookup operation.
// we should not transform on color map here
hints.put(JAI.KEY_TRANSFORM_ON_COLORMAP,Boolean.FALSE);
PlanarImage luImage = LookupDescriptor.create(image, table, hints);
/*
* Now that we have performed the lookup operation we have to remember
* what we stated here above.
*
* If the input image is multiband we will get a multiband image as
* the output of the lookup operation hence we need to perform some form
* of band combination to get the alpha band out of the lookup image.
*
* The way we wanted things to be done is by exploiting the clamping
* behavior that kicks in when we do sums and the like on pixels and
* we overcome the maximum value allowed by the DataBufer DataType.
*/
if (!singleStep) {
// We simply add the three generated bands together in order to get the right.
final double[][] matrix = new double[1][4];
// Values at index 0,1,2 are set to 1.0, value at index 3 is left to 0.
Arrays.fill(matrix[0], 0, 3, 1.0);
luImage = BandCombineDescriptor.create(luImage, matrix, hints);
}
image = BandMergeDescriptor.create(image, luImage, hints);
invalidateStatistics();
return this;
}
/**
* Inverts the pixel values of the {@linkplain #image}.
*
* @see InvertDescriptor
*/
public final ImageWorker invert() {
image = InvertDescriptor.create(image, getRenderingHints());
invalidateStatistics();
return this;
}
/**
* Applies the specified mask over the current {@linkplain #image}. The mask should be
* {@linkplain #binarize() binarized} - if it is not, this method will do it itself.
* Then, for every pixels in the mask with value equals to {@code maskValue}, the
* corresponding pixel in the {@linkplain #image} will be set to the specified
* {@code newValue}.
* <p>
* <strong>Note:</strong> current implementation force the color model to an
* {@linkplain IndexColorModel indexed} one. Future versions may avoid this change.
*
* @param mask
* The mask to apply, as a {@linkplain #binarize() binarized} image.
* @param maskValue
* The mask value to search for ({@code false} for 0 or {@code true} for 1).
* @param newValue
* The new value for every pixels in {@linkplain #image}
* corresponding to {@code maskValue} in the mask.
*
* @return this {@link ImageWorker}.
*
* @todo This now should work only if {@code newValue} is 255
* and {@code maskValue} is {@code false}.
*/
public final ImageWorker mask(RenderedImage mask, final boolean maskValue,
int newValue) {
/*
* Make sure that the underlying image is indexed.
*/
tileCacheEnabled(false);
forceIndexColorModel(true);
final RenderingHints hints = new RenderingHints(JAI.KEY_TILE_CACHE,
null);
/*
* special case for newValue == 255 && !maskValue.
*/
if (newValue == 255 && !maskValue) {
/*
* Build a lookup table in order to make the transparent pixels
* equal to 255 and all the others equal to 0.
*
*/
final byte[] lutData = new byte[256];
// mapping all the non-transparent pixels to opaque
Arrays.fill(lutData, (byte) 0);
// for transparent pixels
lutData[0] = (byte) 255;
final LookupTableJAI lut = new LookupTableJAI(lutData);
mask = LookupDescriptor.create(mask, lut, hints);
/*
* Adding to the other image exploiting the implict clamping
*
*/
image = AddDescriptor.create(image, mask, getRenderingHints());
tileCacheEnabled(true);
invalidateStatistics();
return this;
} else {
// general case
// it has to be binary
if (!isBinary())
binarize();
// now if we mask with 1 we have to invert the mask
if (maskValue)
mask = NotDescriptor.create(mask, new RenderingHints(
JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.FALSE));
// and with the image to zero the interested pixels
tileCacheEnabled(false);
image = AndDescriptor.create(mask, image, getRenderingHints());
// add the new value to the mask
mask = AddConstDescriptor.create(mask, new double[] { newValue },
new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
Boolean.FALSE));
// add the mask to the image to mask with the new value
image = AddDescriptor.create(mask, image, getRenderingHints());
tileCacheEnabled(true);
invalidateStatistics();
return this;
}
}
/**
* Takes two rendered or renderable source images, and adds every pair of pixels, one from
* each source image of the corresponding position and band. See JAI {@link AddDescriptor}
* for details.
*
* @param renderedImage
* the {@link RenderedImage} to be added to this {@link ImageWorker}.
* @return this {@link ImageWorker}.
*
* @see AddDescriptor
*/
public final ImageWorker addImage(final RenderedImage renderedImage) {
image = AddDescriptor.create(image, renderedImage, getRenderingHints());
invalidateStatistics();
return this;
}
/**
* Takes one rendered or renderable image and an array of double constants, and multiplies
* every pixel of the same band of the source by the constant from the corresponding array
* entry. See JAI {@link MultiplyConstDescriptor} for details.
*
* @param inValues
* The constants to be multiplied.
* @return this {@link ImageWorker}.
*
* @see MultiplyConstDescriptor
*/
public final ImageWorker multiplyConst(double[] inValues) {
image = MultiplyConstDescriptor.create(image, inValues, getRenderingHints());
invalidateStatistics();
return this;
}
/**
* Takes one rendered or renderable image and an array of integer constants, and performs a
* bit-wise logical "xor" between every pixel in the same band of the source and the constant
* from the corresponding array entry. See JAI {@link XorConstDescriptor} for details.
*
* @see XorConstDescriptor
*/
public final ImageWorker xorConst(int[] values) {
image = XorConstDescriptor.create(image, values, getRenderingHints());
invalidateStatistics();
return this;
}
/**
* Adds transparency to a preexisting image whose color model is
* {@linkplain IndexColorModel index color model}. For all pixels with the
* value {@code false} in the specified transparency mask, the corresponding
* pixel in the {@linkplain #image} is set to the transparent pixel value.
* All other pixels are left unchanged.
*
* @param alphaChannel
* The mask to apply as a {@linkplain #binarize() binarized} image.
* @param errorDiffusion
* Tells if I should use {@link ErrorDiffusionDescriptor} or
* {@link OrderedDitherDescriptor} JAi operations.
* @return this {@link ImageWorker}.
*
* @see #isTranslucent
* @see #forceBitmaskIndexColorModel
*/
public ImageWorker addTransparencyToIndexColorModel(final RenderedImage alphaChannel,
final boolean errorDiffusion)
{
addTransparencyToIndexColorModel(alphaChannel, true, getTransparentPixel(), errorDiffusion);
return this;
}
/**
* Adds transparency to a preexisting image whose color model is {@linkplain IndexColorModel
* index color model}. First, this method creates a new index color model with the specified
* {@code transparent} pixel, if needed (this method may skip this step if the specified pixel
* is already transparent. Then for all pixels with the value {@code false} in the specified
* transparency mask, the corresponding pixel in the {@linkplain #image} is set to that
* transparent value. All other pixels are left unchanged.
*
* @param alphaChannel
* The mask to apply as a {@linkplain #binarize() binarized} image.
* @param translucent
* {@code true} if {@linkplain Transparency#TRANSLUCENT translucent} images are
* allowed, or {@code false} if the resulting images must be a
* {@linkplain Transparency#BITMASK bitmask}.
* @param transparent
* The value for transparent pixels, to be given to every pixels in the
* {@linkplain #image} corresponding to {@code false} in the mask. The
* special value {@code -1} maps to the last pixel value allowed for the
* {@linkplain IndexedColorModel indexed color model}.
* @param errorDiffusion
* Tells if I should use {@link ErrorDiffusionDescriptor} or
* {@link OrderedDitherDescriptor} JAi operations.
*
* @return this {@link ImageWorker}.
*/
public final ImageWorker addTransparencyToIndexColorModel(final RenderedImage alphaChannel,
final boolean translucent, int transparent, final boolean errorDiffusion)
{
tileCacheEnabled(false);
forceIndexColorModel(errorDiffusion);
tileCacheEnabled(true);
/*
* Prepares hints and layout to use for mask operations. A color model
* hint will be set only if the block below is executed.
*/
final ImageWorker worker = fork(image);
final RenderingHints hints = worker.getRenderingHints();
/*
* Gets the index color model. If the specified 'transparent' value is not fully
* transparent, replaces the color model by a new one with the transparent pixel
* defined. NOTE: the "transparent &= (1 << pixelSize) - 1" instruction below is
* a safety for making sure that the transparent index value can hold in the amount
* of bits allowed for this color model (the mapSize value may not use all bits).
* It works as expected with the -1 special value. It also make sure that
* "transparent + 1" do not exeed the maximum map size allowed.
*/
final boolean forceBitmask;
final IndexColorModel oldCM = (IndexColorModel) image.getColorModel();
final int pixelSize = oldCM.getPixelSize();
transparent &= (1 << pixelSize) - 1;
forceBitmask = !translucent && oldCM.getTransparency() == Transparency.TRANSLUCENT;
if (forceBitmask || oldCM.getTransparentPixel() != transparent) {
final int mapSize = Math.max(oldCM.getMapSize(), transparent + 1);
final byte[][] RGBA = new byte[translucent ? 4 : 3][mapSize];
// Note: we might use less that 256 values.
oldCM.getReds (RGBA[0]);
oldCM.getGreens(RGBA[1]);
oldCM.getBlues (RGBA[2]);
final IndexColorModel newCM;
if (translucent) {
oldCM.getAlphas(RGBA[3]);
RGBA[3][transparent] = 0;
newCM = new IndexColorModel(pixelSize, mapSize, RGBA[0], RGBA[1], RGBA[2], RGBA[3]);
} else {
newCM = new IndexColorModel(pixelSize, mapSize, RGBA[0], RGBA[1], RGBA[2], transparent);
}
/*
* Set the color model hint.
*/
final ImageLayout layout = getImageLayout(hints);
layout.setColorModel(newCM);
worker.setRenderingHint(JAI.KEY_IMAGE_LAYOUT, layout);
}
/*
* Applies the mask, maybe with a color model change.
*/
worker.setRenderingHint(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.FALSE);
worker.mask(alphaChannel, false, transparent);
image = worker.image;
invalidateStatistics();
// All post conditions for this method contract.
assert isIndexed();
assert translucent || !isTranslucent() : translucent;
assert ((IndexColorModel) image.getColorModel()).getAlpha(transparent) == 0;
return this;
}
/**
* If the was not already tiled, tile it. Note that no tiling will be done
* if 'getRenderingHints()' failed to suggest a tile size. This method is
* for internal use by {@link #write} methods only.
*
* @return this {@link ImageWorker}.
*/
public final ImageWorker tile() {
final RenderingHints hints = getRenderingHints();
final ImageLayout layout = getImageLayout(hints);
if (layout.isValid(ImageLayout.TILE_WIDTH_MASK) ||
layout.isValid(ImageLayout.TILE_HEIGHT_MASK))
{
final int type = image.getSampleModel().getDataType();
image = FormatDescriptor.create(image, type, hints);
}
return this;
}
/**
* Writes the {@linkplain #image} to the specified file. This method differs
* from {@link ImageIO#write(String,File)} in a number of ways:
* <p>
* <ul>
* <li>The {@linkplain ImageWriter image writer} to use is inferred from the file
* extension.</li>
* <li>If the image writer accepts {@link File} objects as input, then the {@code file}
* argument is given directly without creating an {@link ImageOutputStream} object.
* This is important for some formats like HDF, which work <em>only</em> with files.</li>
* <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
* <li>If some special processing is needed for a given format, then the corresponding method
* is invoked. Example: {@link #forceIndexColorModelForGIF}.</li>
* </ul>
*
* @return this {@link ImageWorker}.
*/
public final ImageWorker write(final File output) throws IOException {
final String filename = output.getName();
final int dot = filename.lastIndexOf('.');
if (dot < 0) {
throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
}
final String extension = filename.substring(dot + 1).trim();
write(output, ImageIO.getImageWritersBySuffix(extension));
return this;
}
/**
* Writes outs the image contained into this {@link ImageWorker} as a PNG
* using the provided destination, compression and compression rate.
* <p>
* The destination object can be anything providing that we have an
* {@link ImageOutputStreamSpi} that recognizes it.
*
* @param destination
* where to write the internal {@link #image} as a PNG.
* @param compression
* algorithm.
* @param compressionRate
* percentage of compression.
* @param nativeAcc
* should we use native acceleration.
* @param paletted
* should we write the png as 8 bits?
* @return this {@link ImageWorker}.
* @throws IOException
* In case an error occurs during the search for an
* {@link ImageOutputStream} or during the eoncding process.
*
* @todo Current code doesn't check if the writer already accepts the provided destination.
* It wraps it in a {@link ImageOutputStream} inconditionnaly.
*/
public final void writePNG(final Object destination, final String compression,
final float compressionRate, final boolean nativeAcc,
final boolean paletted)
throws IOException
{
// Reformatting this image for PNG.
if (!paletted) {
forceComponentColorModel();
}else{
forceIndexColorModelForGIF(true);
}
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Encoded input image for png writer");
// Getting a writer.
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Getting a writer");
final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("PNG");
if (!it.hasNext()) {
throw new IllegalStateException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
}
ImageWriter writer = it.next();
// Getting a stream.
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Setting write parameters for this writer");
ImageWriteParam iwp = null;
final ImageOutputStream memOutStream = ImageIO.createImageOutputStream(destination);
if(memOutStream==null)
throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1,"stream"));
if (nativeAcc && writer.getClass().getName().equals(
"com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriter"))
{
// Compressing with native.
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Writer is native");
iwp = writer.getDefaultWriteParam();
// Define compression mode
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// best compression
iwp.setCompressionType(compression);
// we can control quality here
iwp.setCompressionQuality(compressionRate);
// destination image type
iwp.setDestinationType(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel()));
} else {
// Compressing with pure Java.
// pure java from native
if (!nativeAcc && it.hasNext() && writer.getClass().getName().equals(
"com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriter"))
{
writer = it.next();
}
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Writer is NOT native");
// Instantiating PNGImageWriteParam
iwp = new PNGImageWriteParam();
// Define compression mode
iwp.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
}
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("About to write png image");
try{
writer.setOutput(memOutStream);
writer.write(null, new IIOImage(image, null, null), iwp);
}
finally{
try{
writer.dispose();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
try{
memOutStream.close();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
}
}
/**
* Writes outs the image contained into this {@link ImageWorker} as a GIF
* using the provided destination, compression and compression rate.
* <p>
* It is worth to point out that the only compressions algorithm availaible
* with the jdk {@link GIFImageWriter} is "LZW" while the compression rates
* have to be confined between 0 and 1. AN acceptable values is usally 0.75f.
* <p>
* The destination object can be anything providing that we have an
* {@link ImageOutputStreamSpi} that recognizes it.
*
* @param destination
* where to write the internal {@link #image} as a gif.
* @param compression
* The name of compression algorithm.
* @param compressionRate
* percentage of compression, as a number between 0 and 1.
* @return this {@link ImageWorker}.
* @throws IOException
* In case an error occurs during the search for an
* {@link ImageOutputStream} or during the eoncding process.
*
* @see #forceIndexColorModelForGIF(boolean)
*/
public final ImageWorker writeGIF(final Object destination,
final String compression,
final float compressionRate)
throws IOException
{
forceIndexColorModelForGIF(true);
final IIORegistry registry = IIORegistry.getDefaultInstance();
Iterator<ImageWriterSpi> it = registry.getServiceProviders(ImageWriterSpi.class, true);
ImageWriterSpi spi = null;
while (it.hasNext()) {
final ImageWriterSpi candidate = it.next();
if (containsFormatName(candidate.getFormatNames(), "gif")) {
if (spi == null) {
spi = candidate;
} else {
final String name = candidate.getClass().getName();
if (name.equals("com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi")) {
spi = candidate;
break;
}
}
}
}
if (spi == null) {
throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
}
final ImageOutputStream stream = ImageIO.createImageOutputStream(destination);
if(stream==null)
throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1,"stream"));
final ImageWriter writer = spi.createWriterInstance();
final ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType(compression);
param.setCompressionQuality(compressionRate);
try{
writer.setOutput(stream);
writer.write(null, new IIOImage(image, null, null), param);
}finally{
try{
stream.close();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
try{
writer.dispose();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
}
return this;
}
/**
* Writes outs the image contained into this {@link ImageWorker} as a JPEG
* using the provided destination , compression and compression rate.
* <p>
* The destination object can be anything providing that we have an
* {@link ImageOutputStreamSpi} that recognizes it.
*
* @param destination
* where to write the internal {@link #image} as a JPEG.
* @param compression
* algorithm.
* @param compressionRate
* percentage of compression.
* @param nativeAcc
* should we use native acceleration.
* @return this {@link ImageWorker}.
* @throws IOException
* In case an error occurs during the search for an
* {@link ImageOutputStream} or during the eoncding process.
*/
public final void writeJPEG(final Object destination, final String compression,
final float compressionRate, final boolean nativeAcc)
throws IOException
{
// Reformatting this image for jpeg.
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Encoding input image to write out as JPEG.");
// go to component color model if needed
ColorModel cm = image.getColorModel();
final boolean hasAlpha = cm.hasAlpha();
forceComponentColorModel();
cm = image.getColorModel();
// rescale to 8 bit
rescaleToBytes();
cm = image.getColorModel();
// remove transparent band
final int numBands = image.getSampleModel().getNumBands();
if (hasAlpha) {
retainBands(numBands - 1);
}
// Getting a writer.
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Getting a JPEG writer and configuring it.");
final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("JPEG");
if (!it.hasNext()) {
throw new IllegalStateException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
}
ImageWriter writer = it.next();
if (!nativeAcc && writer.getClass().getName().equals(
"com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriter"))
{
writer = it.next();
}
if((!PackageUtil.isCodecLibAvailable()||!(writer.getOriginatingProvider() instanceof CLibJPEGImageWriterSpi))
&&
compression.equals("JPEG-LS")
)
throw new IllegalArgumentException(Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2,"compression","JPEG-LS"));
// Compression is available on both lib
final ImageWriteParam iwp = writer.getDefaultWriteParam();
final ImageOutputStream outStream = ImageIO.createImageOutputStream(destination);
if(outStream==null)
throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1,"stream"));
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionType(compression); // Lossy compression.
iwp.setCompressionQuality(compressionRate); // We can control quality here.
if (iwp instanceof JPEGImageWriteParam) {
final JPEGImageWriteParam param = (JPEGImageWriteParam) iwp;
param.setOptimizeHuffmanTables(true);
try {
param.setProgressiveMode(JPEGImageWriteParam.MODE_DEFAULT);
} catch (UnsupportedOperationException e) {
throw (IOException) new IOException().initCause(e);
// TODO: inline cause when we will be allowed to target Java 6.
}
}
if(LOGGER.isLoggable(Level.FINER))
LOGGER.finer("Writing out...");
try{
writer.setOutput(outStream);
// the JDK writer has problems with images that do not start at minx==miny==0
// while the clib writer has issues with tiled images
if ((!nativeAcc && (image.getMinX() != 0 || image.getMinY() != 0)) ||
(nativeAcc && (image.getNumXTiles() > 1 || image.getNumYTiles() > 1))) {
final BufferedImage finalImage= new BufferedImage(
image.getColorModel(),
((WritableRaster)image.getData()).createWritableTranslatedChild(0,0),
image.getColorModel().isAlphaPremultiplied(),null);
writer.write(null, new IIOImage(finalImage, null, null), iwp);
} else {
writer.write(null, new IIOImage(image, null, null), iwp);
}
} finally{
try{
writer.dispose();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
try{
outStream.close();
}catch (Throwable e) {
if(LOGGER.isLoggable(Level.FINEST))
LOGGER.log(Level.FINEST,e.getLocalizedMessage(),e);
}
}
}
/**
* Writes the {@linkplain #image} to the specified output, trying all
* encoders in the specified iterator in the iteration order.
*
* @return this {@link ImageWorker}.
*/
private ImageWorker write(final Object output, final Iterator<? extends ImageWriter> encoders)
throws IOException
{
if (encoders != null) {
while (encoders.hasNext()) {
final ImageWriter writer = encoders.next();
final ImageWriterSpi spi = writer.getOriginatingProvider();
final Class<?>[] outputTypes;
if (spi == null) {
outputTypes = ImageWriterSpi.STANDARD_OUTPUT_TYPE;
} else {
/*
* If the encoder is for some format handled in a special way (e.g. GIF), apply
* the required operation. Note that invoking the same method many time (e.g.
* "forceIndexColorModelForGIF", which could occurs if there is more than one
* GIF encoder registered) should not hurt - all method invocation after the
* first one should be no-op.
*/
final String[] formats = spi.getFormatNames();
if (containsFormatName(formats, "gif")) {
forceIndexColorModelForGIF(true);
} else {
tile();
}
if (!spi.canEncodeImage(image)) {
continue;
}
outputTypes = spi.getOutputTypes();
}
/*
* Now try to set the output directly (if possible), or as an ImageOutputStream if
* the encoder doesn't accept directly the specified output. Note that some formats
* like HDF may not support ImageOutputStream.
*/
final ImageOutputStream stream;
if (acceptInputType(outputTypes, output.getClass())) {
writer.setOutput(output);
stream = null;
} else if (acceptInputType(outputTypes, ImageOutputStream.class)) {
stream = ImageIO.createImageOutputStream(output);
writer.setOutput(stream);
} else {
continue;
}
/*
* Now saves the image.
*/
writer.write(image);
writer.dispose();
if (stream != null) {
stream.close();
}
return this;
}
}
throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
}
/**
* Returns {@code true} if the specified array contains the specified type.
*/
private static boolean acceptInputType(final Class<?>[] types, final Class<?> searchFor) {
for (int i=types.length; --i >= 0;) {
if (searchFor.isAssignableFrom(types[i])) {
return true;
}
}
return false;
}
/**
* Returns {@code true} if the specified array contains the specified string.
*/
private static boolean containsFormatName(final String[] formats, final String searchFor) {
for (int i=formats.length; --i >= 0;) {
if (searchFor.equalsIgnoreCase(formats[i])) {
return true;
}
}
return false;
}
//////// DEBUGING HELP ////////
/**
* Shows the current {@linkplain #image} in a window together with the operation chain as a
* {@linkplain javax.swing.JTree tree}. This method is provided mostly for debugging purpose.
* This method requires the {@code gt2-widgets-swing.jar} file in the classpath.
*
* @throws HeadlessException
* if {@code gt2-widgets-swing.jar} is not on the classpath, or
* if AWT can't create the window components.
* @return this {@link ImageWorker}.
*
* @see org.geotools.gui.swing.image.OperationTreeBrowser#show(RenderedImage)
*/
public final ImageWorker show() throws HeadlessException {
/*
* Uses reflection because the "gt2-widgets-swing.jar" dependency is optional and may not
* be available in the classpath. All the complicated stuff below is simply doing this call:
*
* OperationTreeBrowser.show(image);
*
* Tip: The @see tag in the above javadoc can be used as a check for the existence
* of class and method referenced below. Check for the javadoc warnings.
*/
final Class<?> c;
try {
c = Class.forName("org.geotools.gui.swing.image.OperationTreeBrowser");
} catch (ClassNotFoundException cause) {
final HeadlessException e;
e = new HeadlessException("The \"gt2-widgets-swing.jar\" file is required.");
e.initCause(cause);
throw e;
}
try {
c.getMethod("show", new Class[] {RenderedImage.class}).invoke(null, new Object[] {image});
} catch (InvocationTargetException e) {
final Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw new AssertionError(e);
} catch (Exception e) {
/*
* ClassNotFoundException may be expected, but all other kinds of
* checked exceptions (and they are numerous...) are errors.
*/
throw new AssertionError(e);
}
return this;
}
/**
* Loads the image from the specified file, and {@linkplain #show display}
* it in a window. This method is mostly as a convenient way to test
* operation chains. This method can be invoked from the command line. If an
* optional {@code -operation} argument is provided, the Java method (one of
* the image operations provided in this class) immediately following it is
* executed. Example:
*
* <blockquote><pre>
* java org.geotools.image.ImageWorker -operation binarize <var><filename></var>
* </pre></blockquote>
*/
public static void main(String[] args) {
final Arguments arguments = new Arguments(args);
final String operation = arguments.getOptionalString("-operation");
args = arguments.getRemainingArguments(1);
if (args.length != 0) try {
final ImageWorker worker = new ImageWorker(new File(args[0]));
// Force usage of tile cache for every operations, including intermediate steps.
worker.setRenderingHint(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
if (operation != null) {
worker.getClass().getMethod(operation, (Class[]) null).invoke(worker, (Object[]) null);
}
/*
* TIP: Tests operations here (before the call to 'show()'), if wanted.
*/
worker.show();
} catch (FileNotFoundException e) {
arguments.printSummary(e);
} catch (NoSuchMethodException e) {
arguments.printSummary(e);
} catch (Exception e) {
e.printStackTrace(arguments.err);
}
}
}
|
package com.haulmont.cuba.web.gui.components;
import com.haulmont.bali.datastruct.Pair;
import com.haulmont.bali.util.Dom4j;
import com.haulmont.chile.core.datatypes.Datatype;
import com.haulmont.chile.core.datatypes.impl.BooleanDatatype;
import com.haulmont.chile.core.model.Instance;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.chile.core.model.MetaPropertyPath;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.Field;
import com.haulmont.cuba.gui.components.Formatter;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.data.*;
import com.haulmont.cuba.gui.data.impl.CollectionDatasourceImpl;
import com.haulmont.cuba.gui.data.impl.CollectionDsActionsNotifier;
import com.haulmont.cuba.gui.presentations.Presentations;
import com.haulmont.cuba.gui.presentations.PresentationsImpl;
import com.haulmont.cuba.security.entity.EntityAttrAccess;
import com.haulmont.cuba.security.entity.EntityOp;
import com.haulmont.cuba.security.entity.Presentation;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.App;
import com.haulmont.cuba.web.WebConfig;
import com.haulmont.cuba.web.gui.AbstractFieldFactory;
import com.haulmont.cuba.web.gui.CompositionLayout;
import com.haulmont.cuba.web.gui.components.presentations.TablePresentations;
import com.haulmont.cuba.web.gui.data.CollectionDsWrapper;
import com.haulmont.cuba.web.gui.data.DsManager;
import com.haulmont.cuba.web.gui.data.ItemWrapper;
import com.haulmont.cuba.web.gui.data.PropertyWrapper;
import com.haulmont.cuba.web.toolkit.data.AggregationContainer;
import com.haulmont.cuba.web.toolkit.ui.CheckBox;
import com.haulmont.cuba.web.toolkit.ui.TableSupport;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ShortcutListener;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.*;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import com.haulmont.cuba.web.toolkit.ui.CheckBox;
public abstract class WebAbstractTable<T extends com.haulmont.cuba.web.toolkit.ui.Table>
extends WebAbstractList<T> implements Table {
protected Map<Object, Table.Column> columns = new HashMap<Object, Table.Column>();
protected List<Table.Column> columnsOrder = new ArrayList<Table.Column>();
protected Map<MetaClass, CollectionDatasource> optionsDatasources = new HashMap<MetaClass, CollectionDatasource>();
protected boolean editable;
protected boolean sortable = true;
protected Action itemClickAction;
protected Action enterPressAction;
protected Table.StyleProvider styleProvider;
protected Map<Table.Column, String> requiredColumns = new HashMap<Table.Column, String>();
protected Table.PagingMode pagingMode;
protected Table.PagingProvider pagingProvider;
protected Map<Table.Column, Set<com.haulmont.cuba.gui.components.Field.Validator>> validatorsMap =
new HashMap<Table.Column, Set<com.haulmont.cuba.gui.components.Field.Validator>>();
protected Set<com.haulmont.cuba.gui.components.Field.Validator> tableValidators =
new LinkedHashSet<com.haulmont.cuba.gui.components.Field.Validator>();
protected CompositionLayout componentComposition;
protected HorizontalLayout topPanel;
protected ButtonsPanel buttonsPanel;
protected RowsCount rowsCount;
protected Map<Table.Column, Object> aggregationCells = null;
private boolean usePresentations;
protected Presentations presentations;
protected TablePresentations tablePresentations;
protected DsManager dsManager;
private List<ColumnCollapseListener> columnCollapseListeners = new ArrayList<ColumnCollapseListener>();
@Override
public java.util.List<Table.Column> getColumns() {
return columnsOrder;
}
@Override
public Table.Column getColumn(String id) {
for (Table.Column column : columnsOrder) {
if (column.getId().toString().equals(id))
return column;
}
return null;
}
@Override
public void addColumn(Table.Column column) {
component.addContainerProperty(column.getId(), column.getType(), null);
columns.put(column.getId(), column);
columnsOrder.add(column);
if (column.getWidth() != null) {
component.setColumnWidth(column.getId(), column.getWidth());
}
}
@Override
public void removeColumn(Table.Column column) {
component.removeContainerProperty(column.getId());
//noinspection RedundantCast
columns.remove((MetaPropertyPath) column.getId());
columnsOrder.remove(column);
}
protected void addGeneratedColumn(Object id, Object generator) {
component.addGeneratedColumn(id, (com.vaadin.ui.Table.ColumnGenerator) generator);
}
protected void removeGeneratedColumn(Object id) {
component.removeGeneratedColumn(id);
}
@Override
public boolean isEditable() {
return editable;
}
@Override
public void setEditable(boolean editable) {
this.editable = editable;
if (datasource != null) {
refreshColumns(component.getContainerDataSource());
}
component.setEditable(editable);
}
protected void setEditableColumns(List<MetaPropertyPath> editableColumns) {
component.setEditableColumns(editableColumns.toArray());
}
@Override
public boolean isSortable() {
return sortable;
}
@Override
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
@Override
public void sortBy(Object propertyId, boolean ascending) {
if (isSortable()) {
component.setSortAscending(ascending);
component.setSortContainerPropertyId(propertyId);
component.sort();
}
}
@Override
public RowsCount getRowsCount() {
return rowsCount;
}
@Override
public void setRowsCount(RowsCount rowsCount) {
if (this.rowsCount != null && topPanel != null) {
topPanel.removeComponent(WebComponentsHelper.unwrap(this.rowsCount));
}
this.rowsCount = rowsCount;
if (rowsCount != null) {
if (topPanel == null) {
topPanel = new HorizontalLayout();
topPanel.setWidth("100%");
componentComposition.addComponentAsFirst(topPanel);
}
Component rc = WebComponentsHelper.unwrap(rowsCount);
topPanel.addComponent(rc);
topPanel.setComponentAlignment(rc, com.vaadin.ui.Alignment.BOTTOM_RIGHT);
}
}
@Override
public boolean isAllowMultiStringCells() {
return component.isAllowMultiStringCells();
}
@Override
public void setAllowMultiStringCells(boolean value) {
component.setAllowMultiStringCells(value);
}
@Override
public boolean isAggregatable() {
return component.isAggregatable();
}
@Override
public void setAggregatable(boolean aggregatable) {
component.setAggregatable(aggregatable);
}
@Override
public void setShowTotalAggregation(boolean showAggregation) {
component.setShowTotalAggregation(showAggregation);
}
@Override
public boolean isShowTotalAggregation() {
return component.isShowTotalAggregation();
}
@Override
public Component getComposition() {
return componentComposition;
}
@Override
public float getHeight() {
return componentComposition.getHeight();
}
@Override
public int getHeightUnits() {
return componentComposition.getHeightUnits();
}
@Override
public void setHeight(String height) {
componentComposition.setHeight(height);
}
@Override
public float getWidth() {
return componentComposition.getWidth();
}
@Override
public void setWidth(String width) {
componentComposition.setWidth(width);
}
@Override
public int getWidthUnits() {
return componentComposition.getWidthUnits();
}
@SuppressWarnings({"UnusedDeclaration"})
protected CollectionDatasource getOptionsDatasource(MetaClass metaClass, Table.Column column) {
if (datasource == null)
throw new IllegalStateException("Table datasource is null");
final DsContext dsContext = datasource.getDsContext();
String optDsName = column.getXmlDescriptor().attributeValue("optionsDatasource");
if (StringUtils.isBlank(optDsName)) {
CollectionDatasource ds = optionsDatasources.get(metaClass);
if (ds != null) return ds;
final DataService dataservice = datasource.getDataService();
final String id = metaClass.getName();
final String viewName = null; //metaClass.getName() + ".lookup";
ds = new CollectionDatasourceImpl(dsContext, dataservice, id, metaClass, viewName);
ds.refresh();
optionsDatasources.put(metaClass, ds);
return ds;
} else {
CollectionDatasource ds = dsContext.get(optDsName);
if (ds == null)
throw new IllegalStateException("Options datasource not found: " + optDsName);
return ds;
}
}
protected void initComponent(T component) {
component.setMultiSelect(false);
component.setNullSelectionAllowed(false);
component.setImmediate(true);
component.setValidationVisible(false);
component.setStoreColWidth(true);
component.setStyleName("table"); //It helps us to manage a caption style
component.setPageLength(15);
component.addActionHandler(new ActionsAdapter());
setPagingMode(Table.PagingMode.SCROLLING);
component.addListener(new Property.ValueChangeListener() {
@Override
public void valueChange(Property.ValueChangeEvent event) {
if (datasource == null) return;
final Set selected = getSelected();
if (selected.isEmpty()) {
//noinspection unchecked
datasource.setItem(null);
} else if (selected.size() > 1) {
datasource.setItem(null);
datasource.setItem((Entity) selected.iterator().next());
} else {
//noinspection unchecked
datasource.setItem(null);
datasource.setItem((Entity) selected.iterator().next());
}
}
});
component.addShortcutListener(new ShortcutListener("tableEnter", com.vaadin.event.ShortcutAction.KeyCode.ENTER, null) {
@Override
public void handleAction(Object sender, Object target) {
if (enterPressAction != null) {
enterPressAction.actionPerform(WebAbstractTable.this);
} else {
handleClickAction();
}
}
});
component.addListener(new ItemClickEvent.ItemClickListener() {
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick() && event.getItem() != null) {
handleClickAction();
}
}
});
component.addColumnCollapseListener(new com.haulmont.cuba.web.toolkit.ui.Table.CollapseListener() {
@Override
public void columnCollapsed(Object columnId, boolean collapsed) {
final Column collapsedColumn = getColumn(columnId.toString());
for (ColumnCollapseListener listener : columnCollapseListeners) {
listener.columnCollapsed(collapsedColumn, collapsed);
}
}
});
component.setSelectable(true);
component.setTableFieldFactory(new FieldFactory());
component.setColumnCollapsingAllowed(true);
component.setColumnReorderingAllowed(true);
setEditable(false);
componentComposition = new CompositionLayout(component);
componentComposition.setSpacing(true);
componentComposition.setMargin(false);
componentComposition.setExpandRatio(component, 1);
componentComposition.setSizeFull();
component.setEnableCancelSorting(ConfigProvider.getConfig(WebConfig.class).getEnableCancelTableSorting());
}
protected void handleClickAction() {
Action action = getItemClickAction();
if (action == null) {
action = getAction("edit");
if (action == null) {
action = getAction("view");
}
}
if (action != null && action.isEnabled()) {
Window window = ComponentsHelper.getWindow(WebAbstractTable.this);
if (!(window instanceof Window.Lookup))
action.actionPerform(WebAbstractTable.this);
else if (action.getId().equals(Window.Lookup.LOOKUP_ITEM_CLICK_ACTION_ID)) {
action.actionPerform(WebAbstractTable.this);
}
}
}
protected Collection<MetaPropertyPath> createColumns(com.vaadin.data.Container ds) {
@SuppressWarnings({"unchecked"})
final Collection<MetaPropertyPath> properties = (Collection<MetaPropertyPath>) ds.getContainerPropertyIds();
Window window = ComponentsHelper.getWindow(this);
boolean isLookup = window instanceof Window.Lookup;
for (MetaPropertyPath propertyPath : properties) {
final Table.Column column = columns.get(propertyPath);
if (column != null && !(editable && BooleanUtils.isTrue(column.isEditable()))) {
final String clickAction =
column.getXmlDescriptor() == null ?
null : column.getXmlDescriptor().attributeValue("clickAction");
if (propertyPath.getRange().isClass()) {
if (!isLookup && !StringUtils.isEmpty(clickAction)) {
addGeneratedColumn(propertyPath, new ReadOnlyAssociationGenerator(column));
}
} else if (propertyPath.getRange().isDatatype()) {
if (!isLookup && !StringUtils.isEmpty(clickAction)) {
addGeneratedColumn(propertyPath, new CodePropertyGenerator(column));
} else if (editable && BooleanUtils.isTrue(column.isCalculatable())) {
addGeneratedColumn(propertyPath, new CalculatableColumnGenerator());
} else {
final Datatype datatype = propertyPath.getRange().asDatatype();
if (BooleanDatatype.NAME.equals(datatype.getName()) && column.getFormatter() == null) {
addGeneratedColumn(propertyPath, new ReadOnlyBooleanDatatypeGenerator());
}
}
} else if (propertyPath.getRange().isEnum()) {
// TODO (abramov)
} else {
throw new UnsupportedOperationException();
}
}
}
return properties;
}
protected void refreshColumns(com.vaadin.data.Container ds) {
@SuppressWarnings({"unchecked"})
final Collection<MetaPropertyPath> propertyIds = (Collection<MetaPropertyPath>) ds.getContainerPropertyIds();
for (final MetaPropertyPath id : propertyIds) {
removeGeneratedColumn(id);
}
if (isEditable()) {
final List<MetaPropertyPath> editableColumns = new ArrayList<MetaPropertyPath>(propertyIds.size());
for (final MetaPropertyPath propertyId : propertyIds) {
final Table.Column column = getColumn(propertyId.toString());
if (BooleanUtils.isTrue(column.isEditable())) {
editableColumns.add(propertyId);
}
}
if (!editableColumns.isEmpty()) {
setEditableColumns(editableColumns);
}
} else {
setEditableColumns(Collections.<MetaPropertyPath>emptyList());
}
createColumns(ds);
}
@Override
public void setDatasource(CollectionDatasource datasource) {
UserSession userSession = UserSessionProvider.getUserSession();
if (!userSession.isEntityOpPermitted(datasource.getMetaClass(), EntityOp.READ)) {
component.setVisible(false);
return;
}
final Collection<Object> columns;
if (this.columns.isEmpty()) {
Collection<MetaPropertyPath> paths = MetadataHelper.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass());
for (MetaPropertyPath metaPropertyPath : paths) {
MetaProperty property = metaPropertyPath.getMetaProperty();
if (!property.getRange().getCardinality().isMany() && !MetadataHelper.isSystem(property)) {
Table.Column column = new Table.Column(metaPropertyPath);
column.setCaption(MessageUtils.getPropertyCaption(property));
column.setType(metaPropertyPath.getRangeJavaClass());
Element element = DocumentHelper.createElement("column");
column.setXmlDescriptor(element);
addColumn(column);
}
}
}
columns = this.columns.keySet();
this.datasource = datasource;
this.dsManager = new DsManager(datasource, this);
final CollectionDsWrapper containerDatasource = createContainerDatasource(datasource, getPropertyColumns(), dsManager);
component.setContainerDataSource(containerDatasource);
if (columns == null) {
throw new NullPointerException("Columns cannot be null");
}
List<MetaPropertyPath> editableColumns = null;
if (isEditable()) {
editableColumns = new LinkedList<MetaPropertyPath>();
}
for (final Object columnId : columns) {
final Table.Column column = this.columns.get(columnId);
final String caption;
if (column != null) {
caption = StringUtils.capitalize(column.getCaption() != null ? column.getCaption() : getColumnCaption(columnId));
} else {
caption = StringUtils.capitalize(getColumnCaption(columnId));
}
setColumnHeader(columnId, caption);
if (column != null) {
if (editableColumns != null && column.isEditable() && (columnId instanceof MetaPropertyPath)) {
MetaProperty colMetaProperty = ((MetaPropertyPath) columnId).getMetaProperty();
MetaClass colMetaClass = colMetaProperty.getDomain();
if (userSession.isEntityAttrPermitted(colMetaClass, colMetaProperty.getName(), EntityAttrAccess.MODIFY)) {
editableColumns.add((MetaPropertyPath) column.getId());
}
}
if (column.isCollapsed() && component.isColumnCollapsingAllowed()) {
// try {
component.setColumnCollapsed(column.getId(), true);
}
if (column.getAggregation() != null && isAggregatable()) {
component.addContainerPropertyAggregation(column.getId(),
WebComponentsHelper.convertAggregationType(column.getAggregation().getType()));
}
}
}
if (editableColumns != null && !editableColumns.isEmpty()) {
setEditableColumns(editableColumns);
}
createColumns(containerDatasource);
List<Object> columnsOrder = new ArrayList<Object>();
for (Table.Column column : this.columnsOrder) {
if (column.getId() instanceof MetaPropertyPath) {
MetaProperty colMetaProperty = ((MetaPropertyPath) column.getId()).getMetaProperty();
MetaClass colMetaClass = colMetaProperty.getDomain();
if (userSession.isEntityOpPermitted(colMetaClass, EntityOp.READ)
&& userSession.isEntityAttrPermitted(
colMetaClass, colMetaProperty.getName(), EntityAttrAccess.VIEW)) {
columnsOrder.add(column.getId());
}
} else {
columnsOrder.add(column.getId());
}
if (editable && column.getAggregation() != null
&& (BooleanUtils.isTrue(column.isEditable()) || BooleanUtils.isTrue(column.isCalculatable())))
{
addAggregationCell(column);
}
}
if (aggregationCells != null) {
dsManager.addListener(createAggregationDatasourceListener());
}
setVisibleColumns(getPropertyColumns());
if (UserSessionProvider.getUserSession().isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION)) {
ShowInfoAction action = (ShowInfoAction) getAction(ShowInfoAction.ACTION_ID);
if (action == null) {
action = new ShowInfoAction();
addAction(action);
}
action.setDatasource(datasource);
}
if (rowsCount != null)
rowsCount.setDatasource(datasource);
datasource.addListener(new CollectionDsActionsNotifier(this));
}
private String getColumnCaption(Object columnId) {
if (columnId instanceof MetaPropertyPath)
return ((MetaPropertyPath) columnId).getMetaProperty().getName();
else
return columnId.toString();
}
private List<MetaPropertyPath> getPropertyColumns() {
List<MetaPropertyPath> result = new ArrayList<MetaPropertyPath>();
for (Column column : columnsOrder) {
if (column.getId() instanceof MetaPropertyPath) {
result.add((MetaPropertyPath) column.getId());
}
}
return result;
}
protected abstract CollectionDsWrapper createContainerDatasource(CollectionDatasource datasource, Collection<MetaPropertyPath> columns, DsManager dsManager);
protected void setVisibleColumns(List<?> columnsOrder) {
component.setVisibleColumns(columnsOrder.toArray());
}
protected void setColumnHeader(Object columnId, String caption) {
component.setColumnHeader(columnId, caption);
}
@Override
public void setRowHeaderMode(com.haulmont.cuba.gui.components.Table.RowHeaderMode rowHeaderMode) {
switch (rowHeaderMode) {
case NONE: {
component.setRowHeaderMode(com.vaadin.ui.Table.ROW_HEADER_MODE_HIDDEN);
break;
}
case ICON: {
component.setRowHeaderMode(com.vaadin.ui.Table.ROW_HEADER_MODE_ICON_ONLY);
break;
}
default: {
throw new UnsupportedOperationException();
}
}
}
@Override
public void setRequired(Table.Column column, boolean required, String message) {
if (required)
requiredColumns.put(column, message);
else
requiredColumns.remove(column);
}
@Override
public void addValidator(Table.Column column, final com.haulmont.cuba.gui.components.Field.Validator validator) {
Set<com.haulmont.cuba.gui.components.Field.Validator> validators = validatorsMap.get(column);
if (validators == null) {
validators = new HashSet<com.haulmont.cuba.gui.components.Field.Validator>();
validatorsMap.put(column, validators);
}
validators.add(validator);
}
@Override
public void addValidator(final com.haulmont.cuba.gui.components.Field.Validator validator) {
tableValidators.add(validator);
}
public void validate() throws ValidationException {
for (com.haulmont.cuba.gui.components.Field.Validator tableValidator : tableValidators) {
tableValidator.validate(getSelected());
}
}
@Override
public void setStyleProvider(final Table.StyleProvider styleProvider) {
this.styleProvider = styleProvider;
if (styleProvider == null) {
component.setCellStyleGenerator(null);
return;
}
component.setCellStyleGenerator(new com.vaadin.ui.Table.CellStyleGenerator() {
public String getStyle(Object itemId, Object propertyId) {
@SuppressWarnings({"unchecked"})
final Entity item = datasource.getItem(itemId);
return styleProvider.getStyleName(item, propertyId);
}
});
}
@Override
public void applySettings(Element element) {
final Element columnsElem = element.element("columns");
if (columnsElem != null) {
Object[] oldColumns = component.getVisibleColumns();
List<Object> newColumns = new ArrayList<Object>();
// add columns from saved settings
for (Element colElem : Dom4j.elements(columnsElem, "columns")) {
for (Object column : oldColumns) {
if (column.toString().equals(colElem.attributeValue("id"))) {
newColumns.add(column);
String width = colElem.attributeValue("width");
if (width != null)
component.setColumnWidth(column, Integer.valueOf(width));
String visible = colElem.attributeValue("visible");
if (visible != null)
// try {
if (component.isColumnCollapsingAllowed()) { // throws exception if not
component.setColumnCollapsed(column, !Boolean.valueOf(visible));
}
break;
}
}
}
// add columns not saved in settings (perhaps new)
for (Object column : oldColumns) {
if (!newColumns.contains(column)) {
newColumns.add(column);
}
}
// if the table contains only one column, always show it
if (newColumns.size() == 1) {
// try {
if (component.isColumnCollapsingAllowed()) { // throws exception if not
component.setColumnCollapsed(newColumns.get(0), false);
}
}
component.setVisibleColumns(newColumns.toArray());
if (isSortable()) {
//apply sorting
String sortProp = columnsElem.attributeValue("sortProperty");
if (!StringUtils.isEmpty(sortProp)) {
MetaPropertyPath sortProperty = datasource.getMetaClass().getPropertyEx(sortProp);
if (newColumns.contains(sortProperty)) {
boolean sortAscending = BooleanUtils.toBoolean(columnsElem.attributeValue("sortAscending"));
component.setSortContainerPropertyId(null);
component.setSortAscending(sortAscending);
component.setSortContainerPropertyId(sortProperty);
}
} else {
component.setSortContainerPropertyId(null);
}
}
}
}
@Override
public boolean saveSettings(Element element) {
Element columnsElem = element.element("columns");
if (columnsElem != null)
element.remove(columnsElem);
columnsElem = element.addElement("columns");
Object[] visibleColumns = component.getVisibleColumns();
for (Object column : visibleColumns) {
Element colElem = columnsElem.addElement("columns");
colElem.addAttribute("id", column.toString());
int width = component.getColumnWidth(column);
if (width > -1)
colElem.addAttribute("width", String.valueOf(width));
Boolean visible = !component.isColumnCollapsed(column);
colElem.addAttribute("visible", visible.toString());
}
MetaPropertyPath sortProperty = (MetaPropertyPath) component.getSortContainerPropertyId();
if (sortProperty != null) {
Boolean sortAscending = component.isSortAscending();
columnsElem.addAttribute("sortProperty", sortProperty.toString());
columnsElem.addAttribute("sortAscending", sortAscending.toString());
}
return true;
}
@Override
public void setEnterPressAction(Action action) {
enterPressAction = action;
}
@Override
public Action getEnterPressAction(){
return enterPressAction;
}
@Override
public void setItemClickAction(Action action) {
if (itemClickAction != null) {
removeAction(itemClickAction);
}
itemClickAction = action;
if (!getActions().contains(action)) {
addAction(action);
}
}
@Override
public Action getItemClickAction() {
return itemClickAction;
}
public String getCaption() {
return component.getCaption();
}
public void setCaption(String caption) {
component.setCaption(caption);
}
public Table.PagingMode getPagingMode() {
return pagingMode;
}
@Override
public void setPagingMode(Table.PagingMode pagingMode) {
this.pagingMode = pagingMode;
component.setPagingMode(WebComponentsHelper.convertPagingMode(pagingMode));
if (pagingMode == Table.PagingMode.PAGE) {
setPagingProvider(new DefaultPagingProvider());
}
}
@Override
public void setMultiSelect(boolean multiselect) {
component.setNullSelectionAllowed(multiselect);
super.setMultiSelect(multiselect);
}
@Override
public ButtonsPanel getButtonsPanel() {
return buttonsPanel;
}
@Override
public void setButtonsPanel(ButtonsPanel panel) {
if (buttonsPanel != null && topPanel != null) {
topPanel.removeComponent(WebComponentsHelper.unwrap(buttonsPanel));
}
buttonsPanel = panel;
if (panel != null) {
if (topPanel == null) {
topPanel = new HorizontalLayout();
topPanel.setWidth("100%");
componentComposition.addComponentAsFirst(topPanel);
}
topPanel.addComponent(WebComponentsHelper.unwrap(panel));
}
}
@Override
public void setPagingProvider(final Table.PagingProvider pagingProvider) {
this.pagingProvider = pagingProvider;
component.setPagingProvider(new com.haulmont.cuba.web.toolkit.ui.Table.PagingProvider() {
public String firstCaption() {
return pagingProvider.firstCaption();
}
public String prevCaption() {
return pagingProvider.prevCaption();
}
public String nextCaption() {
return pagingProvider.nextCaption();
}
public String lastCaption() {
return pagingProvider.lastCaption();
}
public String pageLengthSelectorCaption() {
return pagingProvider.pageLengthSelectorCaption();
}
public boolean showPageLengthSelector() {
return pagingProvider.showPageLengthSelector();
}
public int[] pageLengths() {
return pagingProvider.pageLengths();
}
});
}
@Override
public void addGeneratedColumn(String columnId, final ColumnGenerator generator) {
if (columnId == null)
throw new IllegalArgumentException("columnId is null");
if (generator == null)
throw new IllegalArgumentException("generator is null");
MetaPropertyPath targetCol = getDatasource().getMetaClass().getPropertyPath(columnId);
Object generatedColumnId = targetCol != null ? targetCol : columnId;
// replace generator for column if exist
if (component.getColumnGenerator(generatedColumnId) != null)
component.removeGeneratedColumn(generatedColumnId);
component.addGeneratedColumn(
generatedColumnId,
new com.vaadin.ui.Table.ColumnGenerator() {
public Component generateCell(com.vaadin.ui.Table source, Object itemId, Object columnId) {
com.haulmont.cuba.gui.components.Component component = generator.generateCell(WebAbstractTable.this, itemId);
if (component == null)
return null;
else {
Component vComponent = WebComponentsHelper.unwrap(component);
return vComponent;
}
}
}
);
}
@Override
public void addGeneratedColumn(String columnId, ColumnGenerator generator,
Class<? extends com.haulmont.cuba.gui.components.Component> componentClass) {
// web ui doesn't make any improvements with componentClass known
addGeneratedColumn(columnId, generator);
}
@Override
public void removeGeneratedColumn(String columnId) {
MetaPropertyPath targetCol = getDatasource().getMetaClass().getPropertyPath(columnId);
removeGeneratedColumn(targetCol);
}
/**
* {@inheritDoc}
*/
@Override
public void repaint() {
if (datasource != null) {
com.vaadin.data.Container ds = component.getContainerDataSource();
final Collection<MetaPropertyPath> propertyIds = (Collection<MetaPropertyPath>) ds.getContainerPropertyIds();
// added generated columns
final List<Pair<Object, com.vaadin.ui.Table.ColumnGenerator>> columnGenerators =
new LinkedList<Pair<Object, com.vaadin.ui.Table.ColumnGenerator>>();
for (final MetaPropertyPath id : propertyIds) {
com.vaadin.ui.Table.ColumnGenerator generator = component.getColumnGenerator(id);
if (generator != null) {
columnGenerators.add(new Pair<Object, com.vaadin.ui.Table.ColumnGenerator>(id, generator));
}
}
refreshColumns(ds);
// restore generated columns
for (Pair<Object, com.vaadin.ui.Table.ColumnGenerator> generatorEntry : columnGenerators) {
component.addGeneratedColumn(generatorEntry.getFirst(), generatorEntry.getSecond());
}
}
component.requestRepaintAll();
}
protected Map<Object, Object> __aggregate(AggregationContainer container, AggregationContainer.Context context) {
final List<AggregationInfo> aggregationInfos =
new LinkedList<AggregationInfo>();
for (final Object o : container.getAggregationPropertyIds()) {
final MetaPropertyPath propertyId = (MetaPropertyPath) o;
final Table.Column column = columns.get(propertyId);
if (column.getAggregation() != null) {
aggregationInfos.add(column.getAggregation());
}
}
Map<Object, Object> results = ((CollectionDatasource.Aggregatable) datasource).aggregate(
aggregationInfos.toArray(new AggregationInfo[aggregationInfos.size()]),
context.getItemIds()
);
if (aggregationCells != null) {
results = __handleAggregationResults(context, results);
}
return results;
}
protected Map<Object, Object> __handleAggregationResults(AggregationContainer.Context context, Map<Object, Object> results) {
for (final Map.Entry<Object, Object> entry : results.entrySet()) {
final Table.Column column = columns.get(entry.getKey());
com.vaadin.ui.Label cell;
if ((cell = (com.vaadin.ui.Label) aggregationCells.get(column)) != null) {
WebComponentsHelper.setLabelText(cell, entry.getValue(), column.getFormatter());
entry.setValue(cell);
}
}
return results;
}
protected class TablePropertyWrapper extends PropertyWrapper {
private ValueChangeListener calcListener;
private static final long serialVersionUID = -7942046867909695346L;
public TablePropertyWrapper(Object item, MetaPropertyPath propertyPath, DsManager dsManager) {
super(item, propertyPath, dsManager);
}
@Override
public void addListener(ValueChangeListener listener) {
super.addListener(listener);
//A listener of a calculatable property must be only one
if (listener instanceof CalculatablePropertyValueChangeListener) {
if (this.calcListener != null) {
removeListener(calcListener);
}
calcListener = listener;
}
}
@Override
public void removeListener(ValueChangeListener listener) {
super.removeListener(listener);
if (calcListener == listener) {
calcListener = null;
}
}
@Override
public boolean isReadOnly() {
final Table.Column column = WebAbstractTable.this.columns.get(propertyPath);
if (column != null) {
return !editable || !(BooleanUtils.isTrue(column.isEditable()) || BooleanUtils.isTrue(column.isCalculatable()));
} else {
return super.isReadOnly();
}
}
@Override
public void setReadOnly(boolean newStatus) {
super.setReadOnly(newStatus);
}
@Override
public String toString() {
final Table.Column column = WebAbstractTable.this.columns.get(propertyPath);
if (column != null) {
if (column.getFormatter() != null) {
return column.getFormatter().format(getValue());
} else if (column.getXmlDescriptor() != null) {
String captionProperty = column.getXmlDescriptor().attributeValue("captionProperty");
if (!StringUtils.isEmpty(captionProperty)) {
final Object value = getValue();
return this.propertyPath.getRange().isDatatype() ?
this.propertyPath.getRange().asDatatype().format(value) :
value != null
? String.valueOf(((Instance) value).getValue(captionProperty))
: null;
}
}
}
return super.toString();
}
}
protected abstract class LinkGenerator implements com.vaadin.ui.Table.ColumnGenerator, TableSupport.ColumnGenerator {
protected Table.Column column;
public LinkGenerator(Table.Column column) {
this.column = column;
}
public com.vaadin.ui.Component generateCell(AbstractSelect source, final Object itemId, Object columnId) {
final Item item = source.getItem(itemId);
final Property property = item.getItemProperty(columnId);
final Object value = property.getValue();
final com.vaadin.ui.Button component = new Button();
component.setData(value);
component.setCaption(value == null ? "" : property.toString());
component.setStyleName("link");
component.addListener(new Button.ClickListener() {
public void buttonClick(Button.ClickEvent event) {
final Element element = column.getXmlDescriptor();
final String clickAction = element.attributeValue("clickAction");
if (!StringUtils.isEmpty(clickAction)) {
if (clickAction.startsWith("open:")) {
final com.haulmont.cuba.gui.components.IFrame frame = WebAbstractTable.this.getFrame();
String screenName = clickAction.substring("open:".length()).trim();
final Window window = frame.openEditor(screenName, getItem(item, property), WindowManager.OpenType.THIS_TAB);
window.addListener(new Window.CloseListener() {
public void windowClosed(String actionId) {
if (Window.COMMIT_ACTION_ID.equals(actionId) && window instanceof Window.Editor) {
Object item = ((Window.Editor) window).getItem();
if (item instanceof Entity) {
datasource.updateItem((Entity) item);
}
}
}
});
} else if (clickAction.startsWith("invoke:")) {
final com.haulmont.cuba.gui.components.IFrame frame = WebAbstractTable.this.getFrame();
String methodName = clickAction.substring("invoke:".length()).trim();
try {
IFrame controllerFrame = WebComponentsHelper.getControllerFrame(frame);
Method method = controllerFrame.getClass().getMethod(methodName, Object.class);
method.invoke(controllerFrame, getItem(item, property));
} catch (NoSuchMethodException e) {
throw new RuntimeException("Unable to invoke clickAction", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Unable to invoke clickAction", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to invoke clickAction", e);
}
} else {
throw new UnsupportedOperationException("Unsupported clickAction format: " + clickAction);
}
}
}
});
return component;
}
public Component generateCell(com.vaadin.ui.Table source, Object itemId, Object columnId) {
return generateCell(((AbstractSelect) source), itemId, columnId);
}
public Component generateCell(TableSupport source, Object itemId, Object columnId) {
return generateCell(((AbstractSelect) source), itemId, columnId);
}
protected abstract Entity getItem(Item item, Property property);
}
protected class ReadOnlyAssociationGenerator extends LinkGenerator {
public ReadOnlyAssociationGenerator(Table.Column column) {
super(column);
}
protected Entity getItem(Item item, Property property) {
return (Entity) property.getValue();
}
}
protected class CodePropertyGenerator extends LinkGenerator {
public CodePropertyGenerator(Table.Column column) {
super(column);
}
protected Entity getItem(Item item, Property property) {
return ((ItemWrapper) item).getItem();
}
}
private class ReadOnlyDatatypeGenerator implements com.vaadin.ui.Table.ColumnGenerator, TableSupport.ColumnGenerator {
protected Component generateCell(com.vaadin.ui.AbstractSelect source, Object itemId, Object columnId) {
Property property = source.getItem(itemId).getItemProperty(columnId);
final Object value = property.getValue();
final Label label = new Label(value == null ? null : property.toString());
label.setImmediate(true);
return label;
}
public Component generateCell(com.vaadin.ui.Table source, Object itemId, Object columnId) {
return generateCell(((AbstractSelect) source), itemId, columnId);
}
public Component generateCell(TableSupport source, Object itemId, Object columnId) {
return generateCell(((AbstractSelect) source), itemId, columnId);
}
}
private class ReadOnlyBooleanDatatypeGenerator
implements com.vaadin.ui.Table.ColumnGenerator,
TableSupport.ColumnGenerator {
public Component generateCell(com.vaadin.ui.Table source, Object itemId, Object columnId) {
return generateCell((AbstractSelect) source, itemId, columnId);
}
public Component generateCell(TableSupport source, Object itemId, Object columnId) {
return generateCell((AbstractSelect) source, itemId, columnId);
}
protected Component generateCell(AbstractSelect source, Object itemId, Object columnId) {
final Property property = source.getItem(itemId).getItemProperty(columnId);
final Object value = property.getValue();
com.vaadin.ui.Embedded checkBoxImage;
if (BooleanUtils.isTrue((Boolean) value)){
checkBoxImage = new com.vaadin.ui.Embedded("", new ThemeResource("table/img/checkbox-checked.png"));
}
else {
checkBoxImage = new com.vaadin.ui.Embedded("", new ThemeResource("table/img/checkbox-unchecked.png"));
}
return checkBoxImage;
}
}
private class CalculatableColumnGenerator implements com.vaadin.ui.Table.ColumnGenerator, TableSupport.ColumnGenerator {
public Component generateCell(com.vaadin.ui.Table source, Object itemId, Object columnId) {
return generateCell((AbstractSelect) source, itemId, columnId);
}
public Component generateCell(TableSupport source, Object itemId, Object columnId) {
return generateCell((AbstractSelect) source, itemId, columnId);
}
protected Component generateCell(AbstractSelect source, Object itemId, Object columnId) {
CollectionDatasource ds = WebAbstractTable.this.getDatasource();
MetaPropertyPath propertyPath = ds.getMetaClass().getPropertyEx(columnId.toString());
PropertyWrapper propertyWrapper = (PropertyWrapper) source.getContainerProperty(itemId, propertyPath);
Formatter formatter = null;
Table.Column column = WebAbstractTable.this.getColumn(columnId.toString());
if (column != null) {
formatter = column.getFormatter();
}
final Label label = new Label();
WebComponentsHelper.setLabelText(label, propertyWrapper.getValue(), formatter);
label.setWidth("-1px");
//add property change listener that will update a label value
propertyWrapper.addListener(new CalculatablePropertyValueChangeListener(label, formatter));
return label;
}
}
private static class CalculatablePropertyValueChangeListener implements Property.ValueChangeListener {
private Label component;
private Formatter formatter;
private static final long serialVersionUID = 8041384664735759397L;
private CalculatablePropertyValueChangeListener(Label component, Formatter formatter) {
this.component = component;
this.formatter = formatter;
}
public void valueChange(Property.ValueChangeEvent event) {
WebComponentsHelper.setLabelText(component, event.getProperty().getValue(), formatter);
}
}
protected void addAggregationCell(Table.Column column) {
if (aggregationCells == null) {
aggregationCells = new HashMap<Table.Column, Object>();
}
aggregationCells.put(column, createAggregationCell());
}
protected com.vaadin.ui.Label createAggregationCell() {
com.vaadin.ui.Label label = new Label();
label.setWidth("-1px");
label.setParent(component);
return label;
}
protected CollectionDatasourceListener createAggregationDatasourceListener() {
return new AggregationDatasourceListener();
}
protected class AggregationDatasourceListener implements CollectionDatasourceListener<Entity> {
public void collectionChanged(CollectionDatasource ds, Operation operation) {
}
public void itemChanged(Datasource ds, Entity prevItem, Entity item) {
}
public void stateChanged(Datasource ds, Datasource.State prevState, Datasource.State state) {
}
public void valueChanged(Entity source, String property, Object prevValue, Object value) {
final CollectionDatasource ds = WebAbstractTable.this.getDatasource();
component.aggregate(new AggregationContainer.Context(ds.getItemIds()));
}
}
protected class FieldFactory extends AbstractFieldFactory {
@Override
protected Datasource getDatasource() {
return datasource;
}
@Override
protected CollectionDatasource getOptionsDatasource(MetaClass metaClass, MetaPropertyPath propertyPath) {
return WebAbstractTable.this.getOptionsDatasource(metaClass, columns.get(propertyPath));
}
@Override
protected Collection<Field.Validator> getValidators(MetaPropertyPath propertyPath) {
return validatorsMap.get(columns.get(propertyPath));
}
@Override
protected boolean required(MetaPropertyPath propertyPath) {
return requiredColumns.containsKey(columns.get(propertyPath));
}
@Override
protected String requiredMessage(MetaPropertyPath propertyPath) {
return requiredColumns.get(columns.get(propertyPath));
}
@Override
protected Formatter getFormatter(MetaPropertyPath propertyPath) {
Table.Column column = columns.get(propertyPath);
return column.getFormatter();
}
@Override
protected String getFormat(MetaPropertyPath propertyPath) {
Table.Column column = columns.get(propertyPath);
Element formatterElement = column.getXmlDescriptor().element("formatter");
return formatterElement.attributeValue("format");
}
@Override
protected String fieldType(MetaPropertyPath propertyPath) {
return null; //todo gorodnov: implement this method
}
@Override
protected Element getXmlDescriptor(MetaPropertyPath propertyPath) {
Table.Column column = columns.get(propertyPath);
return column.getXmlDescriptor();
}
@Override
protected void initCommon(com.vaadin.ui.Field field, Field cubaField, MetaPropertyPath propertyPath) {
super.initCommon(field, cubaField, propertyPath);
final Table.Column column = columns.get(propertyPath);
final MetaProperty metaProperty;
if (column.getId() != null) {
metaProperty = ((MetaPropertyPath) column.getId()).getMetaProperty();
} else {
metaProperty = null;
}
if (field instanceof com.vaadin.ui.TextField) {
initTextField((com.vaadin.ui.TextField) field, metaProperty, column.getXmlDescriptor());
}
if (cubaField instanceof WebDateField) {
initDateField(field, metaProperty, column.getXmlDescriptor());
}
if (field instanceof CheckBox) {
((CheckBox) field).setLayoutCaption(true);
}
}
}
class DefaultPagingProvider implements Table.PagingProvider {
@Override
public String firstCaption() {
return null;
}
@Override
public String prevCaption() {
return MessageProvider.getMessage(App.class, "paging.prevCaption");
}
@Override
public String nextCaption() {
return MessageProvider.getMessage(App.class, "paging.nextCaption");
}
@Override
public String lastCaption() {
return null;
}
@Override
public String pageLengthSelectorCaption() {
return null;
}
@Override
public boolean showPageLengthSelector() {
return false;
}
@Override
public int[] pageLengths() {
return new int[0];
}
}
protected boolean handleSpecificVariables(Map<String, Object> variables) {
boolean needReload = false;
if (isUsePresentations()) {
final Presentations p = getPresentations();
if (p.getCurrent() != null && p.isAutoSave(p.getCurrent()) && needUpdatePresentation(variables)) {
Element e = p.getSettings(p.getCurrent());
saveSettings(e);
p.setSettings(p.getCurrent(), e);
}
}
return needReload;
}
private boolean needUpdatePresentation(Map<String, Object> variables) {
return variables.containsKey("colwidth") || variables.containsKey("sortcolumn")
|| variables.containsKey("sortascending") || variables.containsKey("columnorder")
|| variables.containsKey("collapsedcolumns") || variables.containsKey("groupedcolumns");
}
protected void paintSpecificContent(PaintTarget target) throws PaintException {
target.addVariable(component, "presentations", isUsePresentations());
if (isUsePresentations()) {
target.startTag("presentations");
tablePresentations.paint(target);
target.endTag("presentations");
}
}
@Override
public List<Table.Column> getNotCollapsedColumns() {
final List<Table.Column> visibleColumns = new ArrayList<Table.Column>(component.getVisibleColumns().length);
Object[] keys = component.getVisibleColumns();
for (final Object key : keys) {
if (!component.isColumnCollapsed(key)) {
visibleColumns.add(columns.get(key));
}
}
return visibleColumns;
}
@Override
public void usePresentations(boolean use) {
usePresentations = use;
}
@Override
public boolean isUsePresentations() {
return usePresentations;
}
@Override
public void loadPresentations() {
if (isUsePresentations()) {
presentations = new PresentationsImpl(this);
tablePresentations = new TablePresentations(this);
} else {
throw new UnsupportedOperationException("Component doesn't use presentations");
}
}
@Override
public Presentations getPresentations() {
if (isUsePresentations()) {
return presentations;
} else {
throw new UnsupportedOperationException("Component doesn't use presentations");
}
}
@Override
public void applyPresentation(Object id) {
if (isUsePresentations()) {
Presentation p = presentations.getPresentation(id);
applyPresentation(p);
} else {
throw new UnsupportedOperationException("Component doesn't use presentations");
}
}
@Override
public void applyPresentationAsDefault(Object id) {
if (isUsePresentations()) {
Presentation p = presentations.getPresentation(id);
if (p != null) {
presentations.setDefault(p);
applyPresentation(p);
}
} else {
throw new UnsupportedOperationException("Component doesn't use presentations");
}
}
protected void applyPresentation(Presentation p) {
presentations.setCurrent(p);
Element settingsElement = presentations.getSettings(p);
applySettings(settingsElement);
component.requestRepaint();
}
@Override
public Object getDefaultPresentationId() {
Presentation def = presentations.getDefault();
return def == null ? null : def.getId();
}
@Override
public void addColumnCollapsedListener(ColumnCollapseListener columnCollapsedListener) {
columnCollapseListeners.add(columnCollapsedListener);
}
@Override
public void removeColumnCollapseListener(ColumnCollapseListener columnCollapseListener) {
columnCollapseListeners.remove(columnCollapseListener);
}
}
|
package name.abuchen.portfolio.model;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.FormatStyle;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import name.abuchen.portfolio.Messages;
import name.abuchen.portfolio.money.Values;
public class AttributeType
{
private static final Pattern PATTERN = Pattern.compile("^([\\d.,-]*)$"); //$NON-NLS-1$
public interface Converter
{
String toString(Object object);
Object fromString(String value);
}
public static class StringConverter implements Converter
{
@Override
public String toString(Object object)
{
return object != null ? (String) object : ""; //$NON-NLS-1$
}
@Override
public Object fromString(String value)
{
return value.trim().length() > 0 ? value.trim() : null;
}
}
private static class LongConverter implements Converter
{
private final DecimalFormat full;
private Values<Long> values;
public LongConverter(Values<Long> values)
{
this.values = values;
this.full = new DecimalFormat("
this.full.setParseBigDecimal(true);
}
@Override
public String toString(Object object)
{
return object != null ? values.format((Long) object) : ""; //$NON-NLS-1$
}
@Override
public Object fromString(String value)
{
try
{
if (value.trim().length() == 0)
return null;
Matcher m = PATTERN.matcher(value);
if (!m.matches())
throw new IllegalArgumentException(MessageFormat.format(Messages.MsgNotANumber, value));
BigDecimal v = (BigDecimal) full.parse(value);
return v.multiply(BigDecimal.valueOf(values.factor())).longValue();
}
catch (ParseException e)
{
throw new IllegalArgumentException(e);
}
}
}
public static class AmountConverter extends LongConverter
{
public AmountConverter()
{
super(Values.Amount);
}
}
public static class AmountPlainConverter extends LongConverter
{
public AmountPlainConverter()
{
super(Values.AmountPlain);
}
}
public static class QuoteConverter extends LongConverter
{
public QuoteConverter()
{
super(Values.Quote);
}
}
public static class ShareConverter extends LongConverter
{
public ShareConverter()
{
super(Values.Share);
}
}
private static class DoubleConverter implements Converter
{
private final NumberFormat full = new DecimalFormat("
private Values<Double> values;
public DoubleConverter(Values<Double> values)
{
this.values = values;
}
@Override
public String toString(Object object)
{
return object != null ? values.format((Double) object) : ""; //$NON-NLS-1$
}
@Override
public Object fromString(String value)
{
try
{
if (value.trim().length() == 0)
return null;
Matcher m = PATTERN.matcher(value);
if (!m.matches())
throw new IllegalArgumentException(MessageFormat.format(Messages.MsgNotANumber, value));
return Double.valueOf(full.parse(value).doubleValue());
}
catch (ParseException e)
{
throw new IllegalArgumentException(e);
}
}
}
public static class PercentConverter extends DoubleConverter
{
public PercentConverter()
{
super(Values.Percent2);
}
@Override
public Object fromString(String value)
{
Double v = (Double) super.fromString(value.replace("%", "")); //$NON-NLS-1$ //$NON-NLS-2$
return BigDecimal.valueOf(v).divide(BigDecimal.valueOf(100)).doubleValue();
}
}
public static class PercentPlainConverter extends DoubleConverter
{
public PercentPlainConverter()
{
super(Values.PercentPlain);
}
}
public static class DateConverter implements Converter
{
private static final DateTimeFormatter[] formatters = new DateTimeFormatter[] {
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT),
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG),
DateTimeFormatter.ofPattern("d.M.yyyy"), //$NON-NLS-1$
DateTimeFormatter.ofPattern("d.M.yy"), //$NON-NLS-1$
DateTimeFormatter.ISO_DATE };
@Override
public String toString(Object object)
{
if (object != null)
return Values.Date.format((LocalDate) object);
else
return ""; //$NON-NLS-1$
}
@Override
public Object fromString(String value)
{
if (value.trim().length() == 0)
return null;
for (DateTimeFormatter formatter : formatters)
{
try
{
return LocalDate.parse(value, formatter);
}
catch (DateTimeParseException ignore)
{
// continue with next formatter
}
}
throw new IllegalArgumentException(MessageFormat.format(Messages.MsgErrorNotAValidDate, value));
}
}
private final String id;
private String name;
private String columnLabel;
private Class<? extends Attributable> target;
private Class<?> type;
/**
* Converter. Do not persist (includes formats, etc.) but recreate out of
* type and value parameters.
*/
private transient Converter converter; // NOSONAR
private String converterClass;
public AttributeType(String id)
{
this.id = id;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getColumnLabel()
{
return columnLabel;
}
public void setColumnLabel(String columnLabel)
{
this.columnLabel = columnLabel;
}
public Class<?> getType()
{
return type;
}
public void setType(Class<?> type)
{
this.type = type;
}
public Class<? extends Attributable> getTarget()
{
return target;
}
public void setTarget(Class<? extends Attributable> target)
{
this.target = target;
}
public boolean supports(Class<? extends Attributable> type)
{
return target != null ? target.isAssignableFrom(type) : true;
}
public void setConverter(Class<? extends Converter> converterClass)
{
this.converterClass = converterClass.getName();
this.converter = null; // in case it was used before
}
public Converter getConverter()
{
try
{
if (converter == null)
converter = (Converter) Class.forName(converterClass).newInstance();
}
catch (InstantiationException | IllegalAccessException | ClassNotFoundException e)
{
throw new IllegalArgumentException(e);
}
return converter;
}
public boolean isNumber()
{
return Number.class.isAssignableFrom(type);
}
@SuppressWarnings("unchecked")
public Comparator<Object> getComparator()
{
return (o1, o2) -> {
if (o1 == null && o2 == null)
return 0;
else if (o1 == null)
return -1;
else if (o2 == null)
return 1;
if (type == Long.class)
return ((Long) o1).compareTo((Long) o2);
else if (type == Double.class)
return ((Double) o1).compareTo((Double) o2);
else if (type == String.class)
return ((String) o1).compareToIgnoreCase((String) o2);
else
return ((Comparable<Object>) o1).compareTo((Comparable<Object>) o2);
};
}
}
|
package org.jasig.portal;
import org.xml.sax.*;
import org.jasig.portal.utils.*;
import org.jasig.portal.services.LogService;
import java.util.Map;
import org.jasig.portal.PropertiesManager;
/**
* This class renders channel content into a SAXBuffer.
* Rendering is done in a separate thread.
* @author Peter Kharchenko
* @version $ Revision: 1.0 $
*/
public class ChannelRenderer
{
public static final boolean POOL_THREADS=PropertiesManager.getPropertyAsBoolean("org.jasig.portal.ChannelRenderer.pool_threads");
public static final boolean CACHE_CHANNELS=PropertiesManager.getPropertyAsBoolean("org.jasig.portal.ChannelRenderer.cache_channels");
public static final int RENDERING_SUCCESSFUL=0;
public static final int RENDERING_FAILED=1;
public static final int RENDERING_TIMED_OUT=2;
protected IChannel channel;
protected ChannelRuntimeData rd;
protected Map channelCache;
protected Map cacheTables;
protected boolean rendering;
protected boolean donerendering;
protected Thread workerThread;
protected ThreadPoolReceipt workerReceipt;
protected Worker worker;
protected long startTime;
protected long timeOut = java.lang.Long.MAX_VALUE;
protected boolean ccacheable;
protected static ThreadPool tp=null;
protected static Map systemCache=null;
private Object cacheWriteLock;
/**
* Default constructor.
* @param chan Channel associated with this ChannelRenderer
*/
public ChannelRenderer (IChannel chan,ChannelRuntimeData runtimeData)
{
this.channel=chan;
this.rd=runtimeData;
rendering = false;
ccacheable=false;
cacheWriteLock=new Object();
if(tp==null && POOL_THREADS) {
ResourceLimits rl=new ResourceLimits();
rl.setOptimalSize(100); // should be on the order of concurrent users
// note the lack of an upper limit
tp=new ThreadPool("renderers",rl);
}
if(systemCache==null) {
systemCache=ChannelManager.systemCache;
}
}
/**
* Sets the channel on which ChannelRenderer is to operate.
*
* @param channel an <code>IChannel</code>
*/
public void setChannel(IChannel channel) {
LogService.instance().log(LogService.ERROR,"ChannelRenderer::setChannel() : channel is being reset!");
this.channel=channel;
if(worker!=null) {
worker.setChannel(channel);
}
// clear channel chace
channelCache=null;
cacheWriteLock=new Object();
}
/**
* Obtains a content cache specific for this channel instance.
*
* @return a key->rendering map for this channel
*/
Map getChannelCache() {
if(channelCache==null) {
if((channelCache=(SoftHashMap)cacheTables.get(channel))==null) {
channelCache=new SoftHashMap(1);
cacheTables.put(channel,channelCache);
}
}
return channelCache;
}
/**
* Set the timeout value
* @param value timeout in milliseconds
*/
public void setTimeout (long value)
{
timeOut = value;
}
public void setCacheTables(Map cacheTables) {
this.cacheTables=cacheTables;
}
/**
* Informs ChannelRenderer that a character caching scheme
* will be used for the current rendering.
* @param setting a <code>boolean</code> value
*/
public void setCharacterCacheable(boolean setting) {
this.ccacheable=setting;
}
/**
* Start rendering of the channel in a new thread.
* Note that rendered information will be accumulated in a
* buffer until outputRendering() function is called.
* startRendering() is a non-blocking function.
*/
public void startRendering ()
{
// start the rendering thread
worker = new Worker (channel,rd);
if(POOL_THREADS) {
// use thread pooling
try {
workerReceipt=tp.execute(worker);
} catch (InterruptedException ie) {
LogService.instance().log(LogService.ERROR,"ChannelRenderer::startRendering() : interupted while waiting for a rendering thread!");
}
} else {
workerThread = new Thread (this.worker);
workerThread.start ();
}
rendering = true;
startTime = System.currentTimeMillis ();
}
/**
* Output channel rendering through a given ContentHandler.
* Note: call of outputRendering() without prior call to startRendering() is equivalent to
* sequential calling of startRendering() and then outputRendering().
* outputRendering() is a blocking function. It will return only when the channel completes rendering
* or fails to render by exceeding allowed rendering time.
* @param out Document Handler that will receive information rendered by the channel.
* @return error code. 0 - successful rendering; 1 - rendering failed; 2 - rendering timedOut;
*/
public int outputRendering (ContentHandler out) throws Throwable
{
if (!rendering)
this.startRendering ();
boolean abandoned=false;
try
{
long wait = timeOut - System.currentTimeMillis () + startTime;
if(POOL_THREADS) {
synchronized(workerReceipt) {
if(wait>0 && !workerReceipt.isJobdone())
workerReceipt.wait(wait);
}
} else {
if (wait > 0)
workerThread.join (wait);
}
}
catch (InterruptedException e)
{
LogService.instance().log(LogService.DEBUG, "ChannelRenderer::outputRendering() : thread waiting on the WorkerThread has been interrupted : "+e);
}
// by this point, if the job is not done, we have to kill it.
// peterk: would be nice to put it on a "death row" instead of
// stop()ing it instantly. (sorry for the analogy). That way
// we could try poking it with interrupt() a few times, give it
// a low priority and see if it can come back up. stop() can
// leave the system in an unstable state :(
if(POOL_THREADS) {
synchronized(workerReceipt) {
if(!workerReceipt.isJobdone()) {
workerReceipt.killJob();
abandoned=true;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::outputRendering() : killed.");
} else {
abandoned=!workerReceipt.isJobsuccessful();
}
}
} else {
if(!worker.done()) {
// kill the working thread
// yes, this is terribly crude and unsafe, but I don't see an alternative
workerThread.stop ();
abandoned=true;
}
}
if (!abandoned && worker.done ())
{
SAX2BufferImpl buffer;
if (worker.successful() && ((buffer=worker.getBuffer())!=null))
{
// unplug the buffer :)
try
{
buffer.setAllHandlers(out);
buffer.outputBuffer();
return RENDERING_SUCCESSFUL;
}
catch (SAXException e) {
// worst case scenario: partial content output :(
LogService.instance().log(LogService.ERROR, "ChannelRenderer::outputRendering() : following SAX exception occured : "+e);
throw e;
}
} else if(worker.successful() && ccacheable && worker.cbuffer!=null){
return RENDERING_SUCCESSFUL;
} else {
// rendering was not successful
Throwable e;
if((e=worker.getThrowable())!=null) throw new InternalPortalException(e);
// should never get there, unless thread.stop() has seriously messed things up for the worker thread.
return RENDERING_FAILED;
}
} else {
Throwable e;
if(POOL_THREADS) {
e = workerReceipt.getThrownException();
} else {
e = worker.getThrowable();
}
if (e != null) {
throw new InternalPortalException(e);
} else {
// Assume rendering has timed out
return RENDERING_TIMED_OUT;
}
}
}
/**
* Requests renderer to complete rendering and return status.
* This does exactly the same things as outputRendering except for the
* actual stream output.
*
* @return an <code>int</code> return status value
*/
public int completeRendering () throws Throwable
{
if (!rendering)
this.startRendering ();
boolean abandoned=false;
try
{
long wait = timeOut - System.currentTimeMillis () + startTime;
if(POOL_THREADS) {
synchronized(workerReceipt) {
if(wait>0 && !workerReceipt.isJobdone())
workerReceipt.wait(wait);
}
} else {
if (wait > 0)
workerThread.join (wait);
}
}
catch (InterruptedException e)
{
LogService.instance().log(LogService.DEBUG, "ChannelRenderer::completeRendering() : thread waiting on the WorkerThread has been interrupted : "+e);
}
// by this point, if the job is not done, we have to kill it.
// peterk: would be nice to put it on a "death row" instead of
// stop()ing it instantly. (sorry for the analogy). That way
// we could try poking it with interrupt() a few times, give it
// a low priority and see if it can come back up. stop() can
// leave the system in an unstable state :(
if(POOL_THREADS) {
synchronized(workerReceipt) {
if(!workerReceipt.isJobdone()) {
workerReceipt.killJob();
abandoned=true;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::completeRendering() : killed.");
} else {
abandoned=!workerReceipt.isJobsuccessful();
}
}
} else {
if(!worker.done()) {
// kill the working thread
// yes, this is terribly crude and unsafe, but I don't see an alternative
workerThread.stop ();
abandoned=true;
}
}
if (!abandoned && worker.done ())
{
SAX2BufferImpl buffer;
if (worker.successful() && (((buffer=worker.getBuffer())!=null) || (ccacheable && worker.cbuffer!=null))) {
return RENDERING_SUCCESSFUL;
} else {
// rendering was not successful
Throwable e;
if((e=worker.getThrowable())!=null) throw new InternalPortalException(e);
// should never get there, unless thread.stop() has seriously messed things up for the worker thread.
return RENDERING_FAILED;
}
} else {
// rendering has timed out
return RENDERING_TIMED_OUT;
}
}
/**
* Returns rendered buffer.
* This method does not perform any status checks, so make sure to call completeRendering() prior to invoking this method.
*
* @return rendered buffer
*/
public SAX2BufferImpl getBuffer() {
if(worker!=null) {
return worker.getBuffer();
} else {
return null;
}
}
/**
* Returns a character output of a channel rendering.
*/
public String getCharacters() {
if(worker!=null) {
return worker.getCharacters();
} else {
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::getCharacters() : worker is null already !");
return null;
}
}
/**
* Sets a character cache for the current rendering.
*/
public void setCharacterCache(String chars) {
if(worker!=null) {
worker.setCharacterCache(chars);
}
}
/**
* I am not really sure if this will take care of the runaway rendering threads.
* The alternative is kill them explicitly in ChannelManager.
*/
protected void finalize () throws Throwable {
if(POOL_THREADS) {
if(workerReceipt!=null && !workerReceipt.isJobdone())
workerReceipt.killJob();
} else {
if (workerThread.isAlive ())
workerThread.stop ();
}
super.finalize ();
}
protected class Worker implements Runnable {
private boolean successful;
private boolean done;
private IChannel channel;
private ChannelRuntimeData rd;
private SAX2BufferImpl buffer;
private String cbuffer;
private Throwable exc=null;
protected class ChannelCacheEntry {
private Object buffer;
private final Object validity;
public ChannelCacheEntry() {
buffer=null;
validity=null;
}
public ChannelCacheEntry(Object buffer,Object validity) {
this.buffer=buffer;
this.validity=validity;
}
}
public Worker (IChannel ch, ChannelRuntimeData runtimeData) {
this.channel=ch; this.rd=runtimeData;
successful = false; done = false;
buffer=null; cbuffer=null;
}
public void setChannel(IChannel ch) {
this.channel=ch;
}
public void run () {
try {
if(rd!=null)
channel.setRuntimeData(rd);
if(CACHE_CHANNELS) {
// try to obtain rendering from cache
if(channel instanceof ICacheable ) {
ChannelCacheKey key=((ICacheable)channel).generateKey();
if(key!=null) {
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
ChannelCacheEntry entry=(ChannelCacheEntry)systemCache.get(key.getKey());
if(entry!=null) {
// found cached page
// check page validity
if(((ICacheable)channel).isCacheValid(entry.validity) && (entry.buffer!=null)) {
// use it
if(ccacheable && (entry.buffer instanceof String)) {
cbuffer=(String)entry.buffer;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : retrieved system-wide cached character content based on a key \""+key.getKey()+"\"");
} else if(entry.buffer instanceof SAX2BufferImpl) {
buffer=(SAX2BufferImpl) entry.buffer;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : retrieved system-wide cached content based on a key \""+key.getKey()+"\"");
}
} else {
// remove it
systemCache.remove(key.getKey());
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : removed system-wide unvalidated cache based on a key \""+key.getKey()+"\"");
}
}
} else {
// by default we assume INSTANCE_KEY_SCOPE
ChannelCacheEntry entry=(ChannelCacheEntry)getChannelCache().get(key.getKey());
if(entry!=null) {
// found cached page
// check page validity
if(((ICacheable)channel).isCacheValid(entry.validity) && (entry.buffer!=null)) {
// use it
if(ccacheable && (entry.buffer instanceof String)) {
cbuffer=(String)entry.buffer;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : retrieved instance-cached character content based on a key \""+key.getKey()+"\"");
} else if(entry.buffer instanceof SAX2BufferImpl) {
buffer=(SAX2BufferImpl) entry.buffer;
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : retrieved instance-cached content based on a key \""+key.getKey()+"\"");
}
} else {
// remove it
getChannelCache().remove(key.getKey());
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : removed unvalidated instance-cache based on a key \""+key.getKey()+"\"");
}
}
}
}
// future work: here we should synchronize based on a particular cache key.
// Imagine a VERY popular cache entry timing out, then portal will attempt
// to re-render the page in many threads (serving many requests) simultaneously.
// If one was to synchronize on writing cache for a particular key, one thread
// would render and others would wait for it to complete.
// check if need to render
if((ccacheable && cbuffer==null && buffer==null) || ((!ccacheable) && buffer==null)) {
// need to render again and cache the output
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML (buffer);
// save cache
if(key!=null) {
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
systemCache.put(key.getKey(),new ChannelCacheEntry(buffer,key.getKeyValidity()));
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : recorded system cache based on a key \""+key.getKey()+"\"");
} else {
getChannelCache().put(key.getKey(),new ChannelCacheEntry(buffer,key.getKeyValidity()));
LogService.instance().log(LogService.DEBUG,"ChannelRenderer.Worker::run() : recorded instance cache based on a key \""+key.getKey()+"\"");
}
}
}
} else {
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML (buffer);
}
} else {
// in the case when channel cache is not enabled
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML (buffer);
}
successful = true;
} catch (Throwable t) {
exc = t;
}
done = true;
}
public boolean successful () {
return this.successful;
}
public SAX2BufferImpl getBuffer() {
return this.buffer;
}
/**
* Returns a character output of a channel rendering.
*/
public String getCharacters() {
if(ccacheable) {
return this.cbuffer;
} else {
LogService.instance().log(LogService.ERROR,"ChannelRenderer.Worker::getCharacters() : attempting to obtain character data while character caching is not enabled !");
return null;
}
}
/**
* Sets a character cache for the current rendering.
*/
public void setCharacterCache(String chars) {
cbuffer=chars;
if(CACHE_CHANNELS) {
// try to obtain rendering from cache
if(channel instanceof ICacheable ) {
ChannelCacheKey key=((ICacheable)channel).generateKey();
if(key!=null) {
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::setCharacterCache() : called on a key \""+key.getKey()+"\"");
ChannelCacheEntry entry=null;
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
entry=(ChannelCacheEntry)systemCache.get(key.getKey());
if(entry==null) {
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::setCharacterCache() : setting character cache buffer based on a system key \""+key.getKey()+"\"");
entry=new ChannelCacheEntry(chars,key.getKeyValidity());
} else {
entry.buffer=chars;
}
systemCache.put(key.getKey(),entry);
} else {
// by default we assume INSTANCE_KEY_SCOPE
entry=(ChannelCacheEntry)getChannelCache().get(key.getKey());
if(entry==null) {
LogService.instance().log(LogService.DEBUG,"ChannelRenderer::setCharacterCache() : no existing cache on a key \""+key.getKey()+"\"");
entry=new ChannelCacheEntry(chars,key.getKeyValidity());
} else {
entry.buffer=chars;
}
getChannelCache().put(key.getKey(),entry);
}
} else {
LogService.instance().log(LogService.WARN,"ChannelRenderer::setCharacterCache() : channel cache key is null !");
}
}
}
}
public boolean done () {
return this.done;
}
public Throwable getThrowable() {
return exc;
}
}
}
|
// $OldId: AddAccessors.java,v 1.2 2002/11/21 14:14:31 schinz Exp $
package scalac.transformer;
import scalac.*;
import scalac.ast.*;
import scalac.typechecker.*;
import scalac.symtab.*;
import scalac.util.*;
import java.util.*;
/**
* Add private accessor functions for all class constructor arguments
* which are accessed from within the class' methods, or nested
* classes.
*
* @author Michel Schinz
* @version 1.0
*/
public class AddAccessors extends Transformer {
public AddAccessors(Global global, PhaseDescriptor descr) {
super(global, descr);
}
protected Name valName(Symbol sym) {
return Name.fromString(sym.name.toString() + "$");
}
protected final HashMap/*<Symbol,Symbol>*/ accessorMap = new HashMap();
protected boolean inClassContext = true;
protected Symbol accessor(Symbol sym) {
Symbol accessor = (Symbol)accessorMap.get(sym);
if (accessor == null) {
accessor = new TermSymbol(sym.pos,
sym.name,
sym.classOwner(),
Modifiers.STABLE
| Modifiers.ACCESSOR
| Modifiers.PRIVATE);
accessor.setType(Type.MethodType(Symbol.EMPTY_ARRAY, sym.type()));
accessorMap.put(sym, accessor);
}
return accessor;
}
public Tree transform(Tree tree) {
switch (tree) {
case ClassDef(int mods,
Name name,
Tree.TypeDef[] tparams,
Tree.ValDef[][] vparams,
Tree tpe,
Tree.Template impl): {
Symbol clsSym = tree.symbol();
Symbol constrSym = clsSym.constructor();
LinkedList/*<Tree>*/ newBody =
new LinkedList(Arrays.asList(transform(impl.body)));
// Add value definitions and accessors for all constructor
// arguments which were found in the body of the class.
assert vparams.length == 1;
Tree.ValDef[] params = vparams[0];
Scope newMembers = new Scope(clsSym.members());
for (int i = 0; i < params.length; ++i) {
Symbol paramSym = params[i].symbol();
if (accessorMap.containsKey(paramSym)) {
Symbol accessorSym = (Symbol)accessorMap.get(paramSym);
Symbol valSym = new TermSymbol(paramSym.pos,
valName(paramSym),
clsSym,
Modifiers.PRIVATE);
valSym.setType(paramSym.type());
newBody.addFirst(gen.DefDef(accessorSym, gen.Ident(valSym)));
newMembers.enter(accessorSym);
newBody.addFirst(gen.ValDef(valSym, gen.Ident(paramSym)));
newMembers.enter(valSym);
}
}
// Update class type with new values/accessors.
switch (clsSym.info()) {
case CompoundType(Type[] basetypes, Scope members):
clsSym.updateInfo(Type.compoundType(basetypes, newMembers, clsSym));
break;
default:
Debug.abort("unexpected type", clsSym.info());
}
assert inClassContext;
inClassContext = false;
Tree[] newParents = transform(impl.parents);
inClassContext = true;
Tree[] newBodyA = (Tree[])newBody.toArray(new Tree[newBody.size()]);
return copy.ClassDef(tree,
mods,
name,
transform(tparams),
transform(vparams),
transform(tpe),
copy.Template(impl, newParents, newBodyA));
}
case Select(Tree qualifier, Name selector): {
Symbol sym = tree.symbol();
if (sym.owner().isPrimaryConstructor())
return gen.Apply(gen.Select(transform(qualifier), accessor(sym)),
Tree.EMPTY_ARRAY);
else
return copy.Select(tree, transform(qualifier), selector);
}
case Ident(Name name): {
Symbol sym = tree.symbol();
if (inClassContext
&& name.isTermName()
&& sym.owner().isPrimaryConstructor())
return gen.Apply(gen.Ident(accessor(sym)), Tree.EMPTY_ARRAY);
else
return copy.Ident(tree, name);
}
default:
return super.transform(tree);
}
}
}
|
package org.mwc.debrief.lite;
/**
* @author Ayesha <ayesha.ma@gmail.com>
*
*/
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import org.mwc.debrief.lite.util.ManifestUtils;
public class DisplaySplash extends JFrame implements ActionListener, Runnable
{
private static String debriefVersion;
static
{
debriefVersion = ManifestUtils.readManifestVersion();
}
private static final long serialVersionUID = 1L;
private static void renderSplashFrame(final Graphics2D g,
final String message)
{
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 140, 300, 80);
g.setPaintMode();
g.setColor(Color.RED);
g.drawString(message, 20, 170);
}
private static void renderVersion(final Graphics2D g)
{
g.setComposite(AlphaComposite.Clear);
g.fillRect(120, 140, 600, 150);
g.setPaintMode();
g.setColor(Color.BLACK);
if (debriefVersion == null)
{
debriefVersion = "Dev Mode";
}
g.drawString(debriefVersion, 330, 170);
}
private final SplashScreen splash;
@SuppressWarnings("unused")
private int numTasks;
public DisplaySplash(final int numTasks)
{
super();
this.numTasks = numTasks;
splash = SplashScreen.getSplashScreen();
if (splash == null)
{
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
if (splash.isVisible())
{
final Graphics2D g = splash.createGraphics();
if (g == null)
{
System.out.println("g is null");
return;
}
System.out.println("version updated:" + debriefVersion);
renderVersion(splash.createGraphics());
}
}
@Override
public void actionPerformed(final ActionEvent ae)
{
System.exit(0);
}
@SuppressWarnings("unused")
private void closeSplash()
{
try
{
if (splash != null && splash.isVisible())
{
splash.close();
}
}
catch (final Exception e)
{
// ignore - we're closing anyway
}
toFront();
}
@Override
public void run()
{
final String[] tasks =
{"Loading map content", "Initializing Debrief Lite", "Creating map pane",
"Initializing the screen", "Done.."};
if (splash != null)
{
final Graphics2D g = splash.createGraphics();
if (g == null)
{
System.out.println("g is null");
return;
}
for (int i = 0; i < tasks.length; i++)
{
try
{
renderSplashFrame(g, tasks[i]);
splash.update();
Thread.sleep(900);
}
catch (final InterruptedException e)
{
}
}
}
else
{
showSplashError();
}
}
private void showSplashError()
{
System.err.println(
"Path for splash screen image should be provided in command path: -splash:src/main/java/images/splash.gif");
}
public void updateMessage(final String message)
{
numTasks
if (splash != null && splash.isVisible())
{
final Graphics2D g = splash.createGraphics();
if (g == null)
{
System.out.println("g is null");
return;
}
System.out.println("Message updated:" + message);
renderSplashFrame(g, message);
}
else
{
showSplashError();
}
}
}
|
package com.intellij.analysis;
import com.intellij.find.FindSettings;
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.util.RadioUpDownListener;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.ui.TitledSeparator;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
public class BaseAnalysisActionDialog extends DialogWrapper {
private JPanel myPanel;
private final String myFileName;
private final String myModuleName;
private JRadioButton myProjectButton;
private JRadioButton myModuleButton;
private JRadioButton myUncommittedFilesButton;
private JRadioButton myCustomScopeButton;
private JRadioButton myFileButton;
private ScopeChooserCombo myScopeCombo;
private JCheckBox myInspectTestSource;
private JComboBox<String> myChangeLists;
private TitledSeparator myTitledSeparator;
private final Project myProject;
private final boolean myRememberScope;
private final String myAnalysisNoon;
private ButtonGroup myGroup;
private static final String ALL = AnalysisScopeBundle.message("scope.option.uncommitted.files.all.changelists.choice");
private final AnalysisUIOptions myAnalysisOptions;
@Nullable private final PsiElement myContext;
public BaseAnalysisActionDialog(@NotNull String title,
@NotNull String analysisNoon,
@NotNull Project project,
@NotNull final AnalysisScope scope,
@Nullable Module module,
final boolean rememberScope,
@NotNull AnalysisUIOptions analysisUIOptions,
@Nullable PsiElement context) {
//noinspection deprecation
this(title, analysisNoon, project, scope, module == null ? null : module.getName(), rememberScope, analysisUIOptions, context);
}
@Deprecated
public BaseAnalysisActionDialog(@NotNull String title,
@NotNull String analysisNoon,
@NotNull Project project,
@NotNull final AnalysisScope scope,
final String moduleName,
final boolean rememberScope,
@NotNull AnalysisUIOptions analysisUIOptions,
@Nullable PsiElement context) {
super(true);
//noinspection BoundFieldAssignment
myGroup = new ButtonGroup();
myGroup.add(myProjectButton);
myGroup.add(myModuleButton);
myGroup.add(myUncommittedFilesButton);
myGroup.add(myFileButton);
myGroup.add(myCustomScopeButton);
Disposer.register(myDisposable, myScopeCombo);
myAnalysisOptions = analysisUIOptions;
myContext = context;
if (!analysisUIOptions.ANALYZE_TEST_SOURCES) {
myAnalysisOptions.ANALYZE_TEST_SOURCES = scope.isAnalyzeTestsByDefault();
}
myProject = project;
myFileName = scope.getScopeType() == AnalysisScope.PROJECT ? null : scope.getShortenName();
myModuleName = moduleName;
myRememberScope = rememberScope;
myAnalysisNoon = analysisNoon;
init();
setTitle(title);
onScopeRadioButtonPressed();
}
@Override
protected JComponent createCenterPanel() {
myTitledSeparator.setText(myAnalysisNoon);
//include test option
myInspectTestSource.setSelected(myAnalysisOptions.ANALYZE_TEST_SOURCES);
myInspectTestSource.setVisible(ModuleUtil.isSupportedRootType(myProject, JavaSourceRootType.TEST_SOURCE));
//module scope if applicable
myModuleButton.setText(AnalysisScopeBundle.message("scope.option.module.with.mnemonic", myModuleName));
boolean useModuleScope = false;
myModuleButton.setVisible(myModuleName != null && ModuleManager.getInstance(myProject).getModules().length > 1);
boolean useUncommitedFiles = false;
final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
final boolean hasVCS = !changeListManager.getAffectedFiles().isEmpty();
myUncommittedFilesButton.setVisible(hasVCS);
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement(ALL);
final List<? extends ChangeList> changeLists = changeListManager.getChangeListsCopy();
for (ChangeList changeList : changeLists) {
model.addElement(changeList.getName());
}
myChangeLists.setRenderer(new ListCellRendererWrapper<String>() {
@Override
public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) {
int availableWidth = myPanel.getWidth() - myUncommittedFilesButton.getWidth() - JBUI.scale(10);
if (availableWidth <= 0) {
availableWidth = JBUI.scale(200);
}
if (list.getFontMetrics(list.getFont()).stringWidth(value) < availableWidth) {
setText(value);
}
else {
setText(StringUtil.trimLog(value, 50));
}
}
});
myChangeLists.setModel(model);
myChangeLists.setEnabled(myUncommittedFilesButton.isSelected());
myChangeLists.setVisible(hasVCS);
//file/package/directory/module scope
if (myFileName != null) {
myFileButton.setText(myFileName);
myFileButton.setMnemonic(myFileName.charAt(getSelectedScopeMnemonic()));
} else {
myFileButton.setVisible(false);
}
VirtualFile file = PsiUtilCore.getVirtualFile(myContext);
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
boolean searchInLib = file != null && (fileIndex.isInLibraryClasses(file) || fileIndex.isInLibrarySource(file));
String preselect = StringUtil.isEmptyOrSpaces(myAnalysisOptions.CUSTOM_SCOPE_NAME)
? FindSettings.getInstance().getDefaultScopeName()
: myAnalysisOptions.CUSTOM_SCOPE_NAME;
if (searchInLib && GlobalSearchScope.projectScope(myProject).getDisplayName().equals(preselect)) {
preselect = GlobalSearchScope.allScope(myProject).getDisplayName();
}
if (GlobalSearchScope.allScope(myProject).getDisplayName().equals(preselect) && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.CUSTOM) {
myAnalysisOptions.CUSTOM_SCOPE_NAME = preselect;
searchInLib = true;
}
boolean someButtonEnabled = false;
if (myRememberScope) {
switch (myAnalysisOptions.SCOPE_TYPE) {
case AnalysisScope.PROJECT:
someButtonEnabled = select(myProjectButton);
break;
case AnalysisScope.MODULE:
someButtonEnabled = select(myModuleButton);
break;
case AnalysisScope.FILE:
someButtonEnabled = select(myFileButton);
break;
case AnalysisScope.UNCOMMITTED_FILES:
someButtonEnabled = select(myUncommittedFilesButton);
break;
case AnalysisScope.CUSTOM:
someButtonEnabled = select(myCustomScopeButton);
break;
}
} else {
if (!(someButtonEnabled = select(myFileButton))) {
select(myModuleButton);
}
}
if (!someButtonEnabled) {
select(myProjectButton);
}
myScopeCombo.init(myProject, searchInLib, true, preselect);
myScopeCombo.setCurrentSelection(false);
myScopeCombo.setEnabled(myCustomScopeButton.isSelected());
final ActionListener radioButtonPressed = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onScopeRadioButtonPressed();
}
};
final Enumeration<AbstractButton> enumeration = myGroup.getElements();
while (enumeration.hasMoreElements()) {
enumeration.nextElement().addActionListener(radioButtonPressed);
}
//additional panel - inspection profile chooser
JPanel wholePanel = new JPanel(new BorderLayout());
wholePanel.add(myPanel, BorderLayout.NORTH);
final JComponent additionalPanel = getAdditionalActionSettings(myProject);
if (additionalPanel!= null){
wholePanel.add(additionalPanel, BorderLayout.CENTER);
}
new RadioUpDownListener(myProjectButton, myModuleButton, myUncommittedFilesButton, myFileButton, myCustomScopeButton);
return wholePanel;
}
private int getSelectedScopeMnemonic() {
final int fileIdx = StringUtil.indexOfIgnoreCase(myFileName, "file", 0);
if (fileIdx > -1) {
return fileIdx;
}
final int dirIdx = StringUtil.indexOfIgnoreCase(myFileName, "directory", 0);
if (dirIdx > -1) {
return dirIdx;
}
return 0;
}
private void onScopeRadioButtonPressed() {
myScopeCombo.setEnabled(myCustomScopeButton.isSelected());
myChangeLists.setEnabled(myUncommittedFilesButton.isSelected());
}
@Override
public JComponent getPreferredFocusedComponent() {
final Enumeration<AbstractButton> enumeration = myGroup.getElements();
while (enumeration.hasMoreElements()) {
final AbstractButton button = enumeration.nextElement();
if (button.isSelected()) {
return button;
}
}
return myPanel;
}
@Nullable
protected JComponent getAdditionalActionSettings(final Project project) {
return null;
}
public boolean isProjectScopeSelected() {
return myProjectButton.isSelected();
}
public boolean isModuleScopeSelected() {
return myModuleButton != null && myModuleButton.isSelected();
}
public boolean isUncommittedFilesSelected(){
return myUncommittedFilesButton != null && myUncommittedFilesButton.isSelected();
}
@Nullable
public SearchScope getCustomScope(){
if (myCustomScopeButton.isSelected()){
return myScopeCombo.getSelectedScope();
}
return null;
}
public boolean isInspectTestSources(){
return myInspectTestSource.isSelected();
}
@NotNull
public AnalysisScope getScope(@NotNull AnalysisUIOptions uiOptions, @NotNull AnalysisScope defaultScope, @NotNull Project project, Module module) {
AnalysisScope scope;
if (isProjectScopeSelected()) {
scope = new AnalysisScope(project);
uiOptions.SCOPE_TYPE = AnalysisScope.PROJECT;
}
else {
final SearchScope customScope = getCustomScope();
if (customScope != null) {
scope = new AnalysisScope(customScope, project);
uiOptions.SCOPE_TYPE = AnalysisScope.CUSTOM;
uiOptions.CUSTOM_SCOPE_NAME = customScope.getDisplayName();
}
else if (isModuleScopeSelected()) {
scope = new AnalysisScope(module);
uiOptions.SCOPE_TYPE = AnalysisScope.MODULE;
}
else if (isUncommittedFilesSelected()) {
final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
List<VirtualFile> files;
if (myChangeLists.getSelectedItem() == ALL) {
files = changeListManager.getAffectedFiles();
}
else {
files = new ArrayList<>();
for (ChangeList list : changeListManager.getChangeListsCopy()) {
if (!Comparing.strEqual(list.getName(), (String)myChangeLists.getSelectedItem())) continue;
final Collection<Change> changes = list.getChanges();
for (Change change : changes) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
final VirtualFile vFile = afterRevision.getFile().getVirtualFile();
if (vFile != null) {
files.add(vFile);
}
}
}
}
}
scope = new AnalysisScope(project, new HashSet<>(files));
uiOptions.SCOPE_TYPE = AnalysisScope.UNCOMMITTED_FILES;
}
else {
scope = defaultScope;
uiOptions.SCOPE_TYPE = defaultScope.getScopeType();//just not project scope
}
}
uiOptions.ANALYZE_TEST_SOURCES = isInspectTestSources();
scope.setIncludeTestSource(isInspectTestSources());
FindSettings.getInstance().setDefaultScopeName(scope.getDisplayName());
return scope;
}
private static boolean select(JRadioButton button) {
if (button.isVisible()) {
button.setSelected(true);
return true;
}
return false;
}
}
|
package com.intellij.util.lang;
import com.intellij.openapi.util.io.FileUtilRt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author Dmitry Avdeev
*/
public final class JarMemoryLoader {
/** Special entry to keep the number of reordered classes in jar. */
public static final String SIZE_ENTRY = "META-INF/jb/$$size$$";
private final Map<String, Resource> resources;
private JarMemoryLoader(@NotNull Map<String, Resource> resources) {
this.resources = resources;
}
public synchronized Resource getResource(@NotNull String entryName) {
return resources.remove(entryName);
}
@Nullable static JarMemoryLoader load(@NotNull ZipFile zipFile, @NotNull URL baseUrl, @Nullable JarLoader attributesProvider) throws IOException {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
if (!entries.hasMoreElements()) {
return null;
}
ZipEntry sizeEntry = entries.nextElement();
if (sizeEntry == null || !sizeEntry.getName().equals(SIZE_ENTRY)) {
return null;
}
byte[] bytes = FileUtilRt.loadBytes(zipFile.getInputStream(sizeEntry), 2);
int size = ((bytes[1] & 0xFF) << 8) + (bytes[0] & 0xFF);
Map<String, Resource> map = new HashMap<String, Resource>();
for (int i = 0; i < size && entries.hasMoreElements(); i++) {
ZipEntry entry = entries.nextElement();
MemoryResource resource = MemoryResource.load(baseUrl, zipFile, entry, attributesProvider != null ? attributesProvider.getAttributes() : null);
map.put(entry.getName(), resource);
}
return new JarMemoryLoader(map);
}
}
|
package com.intellij.vcs.log.data;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Function;
import com.intellij.util.io.*;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.impl.FatalErrorHandler;
import com.intellij.vcs.log.impl.HashImpl;
import com.intellij.vcs.log.impl.VcsRefImpl;
import com.intellij.vcs.log.util.PersistentUtil;
import com.intellij.vcs.log.util.StorageId;
import gnu.trove.TObjectIntHashMap;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
/**
* Supports the int <-> Hash and int <-> VcsRef persistent mappings.
*/
public final class VcsLogStorageImpl implements Disposable, VcsLogStorage {
@NotNull private static final Logger LOG = Logger.getInstance(VcsLogStorage.class);
@NotNull @NonNls private static final String HASHES_STORAGE = "hashes";
@NotNull @NonNls private static final String REFS_STORAGE = "refs";
@NotNull @NonNls private static final String STORAGE = "storage";
@NotNull public static final VcsLogStorage EMPTY = new EmptyLogStorage();
public static final int VERSION = 8;
public static final int NO_INDEX = -1;
private static final int REFS_VERSION = 2;
@NotNull private final MyPersistentBTreeEnumerator myCommitIdEnumerator;
@NotNull private final PersistentEnumeratorBase<VcsRef> myRefsEnumerator;
@NotNull private final FatalErrorHandler myExceptionReporter;
private volatile boolean myDisposed = false;
public VcsLogStorageImpl(@NotNull Project project,
@NotNull Map<VirtualFile, VcsLogProvider> logProviders,
@NotNull FatalErrorHandler exceptionReporter,
@NotNull Disposable parent) throws IOException {
myExceptionReporter = exceptionReporter;
List<VirtualFile> roots = StreamEx.ofKeys(logProviders).sortedBy(VirtualFile::getPath).toList();
String logId = PersistentUtil.calcLogId(project, logProviders);
MyCommitIdKeyDescriptor commitIdKeyDescriptor = new MyCommitIdKeyDescriptor(roots);
StorageId hashesStorageId = new StorageId(project.getName(), HASHES_STORAGE, logId, VERSION);
myCommitIdEnumerator = IOUtil.openCleanOrResetBroken(() -> new MyPersistentBTreeEnumerator(hashesStorageId, commitIdKeyDescriptor),
hashesStorageId.getStorageFile(STORAGE).toFile());
VcsRefKeyDescriptor refsKeyDescriptor = new VcsRefKeyDescriptor(logProviders, commitIdKeyDescriptor);
StorageId refsStorageId = new StorageId(project.getName(), REFS_STORAGE, logId, VERSION + REFS_VERSION);
myRefsEnumerator = IOUtil.openCleanOrResetBroken(() -> new PersistentBTreeEnumerator<>(refsStorageId.getStorageFile(STORAGE),
refsKeyDescriptor, Page.PAGE_SIZE,
null, refsStorageId.getVersion()),
refsStorageId.getStorageFile(STORAGE).toFile());
Disposer.register(parent, this);
}
@NotNull
public static Function<Integer, Hash> createHashGetter(@NotNull VcsLogStorage storage) {
return commitIndex -> {
CommitId commitId = storage.getCommitId(commitIndex);
if (commitId == null) return null;
return commitId.getHash();
};
}
@Nullable
private CommitId doGetCommitId(int index) throws IOException {
return myCommitIdEnumerator.valueOf(index);
}
private int getOrPut(@NotNull Hash hash, @NotNull VirtualFile root) throws IOException {
return myCommitIdEnumerator.enumerate(new CommitId(hash, root));
}
@Override
public int getCommitIndex(@NotNull Hash hash, @NotNull VirtualFile root) {
checkDisposed();
try {
return getOrPut(hash, root);
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
}
return NO_INDEX;
}
@Override
@Nullable
public CommitId getCommitId(int commitIndex) {
checkDisposed();
try {
CommitId commitId = doGetCommitId(commitIndex);
if (commitId == null) {
myExceptionReporter.consume(this, new RuntimeException("Unknown commit index: " + commitIndex));
}
return commitId;
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
}
return null;
}
@Override
public boolean containsCommit(@NotNull CommitId id) {
checkDisposed();
try {
return myCommitIdEnumerator.contains(id);
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
}
return false;
}
@Override
public void iterateCommits(@NotNull Predicate<? super CommitId> consumer) {
checkDisposed();
try {
myCommitIdEnumerator.iterateData(new CommonProcessors.FindProcessor<CommitId>() {
@Override
protected boolean accept(CommitId commitId) {
return !consumer.test(commitId);
}
});
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
}
}
@Override
public int getRefIndex(@NotNull VcsRef ref) {
checkDisposed();
try {
return myRefsEnumerator.enumerate(ref);
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
}
return NO_INDEX;
}
@Nullable
@Override
public VcsRef getVcsRef(int refIndex) {
checkDisposed();
try {
return myRefsEnumerator.valueOf(refIndex);
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
return null;
}
}
@Override
public void flush() {
checkDisposed();
myCommitIdEnumerator.force();
myRefsEnumerator.force();
}
@Override
public void dispose() {
try {
myDisposed = true;
myCommitIdEnumerator.close();
myRefsEnumerator.close();
}
catch (IOException e) {
LOG.warn(e);
}
}
private void checkDisposed() {
if (myDisposed) throw new ProcessCanceledException();
}
private static class MyCommitIdKeyDescriptor implements KeyDescriptor<CommitId> {
@NotNull private final List<? extends VirtualFile> myRoots;
@NotNull private final TObjectIntHashMap<VirtualFile> myRootsReversed;
MyCommitIdKeyDescriptor(@NotNull List<? extends VirtualFile> roots) {
myRoots = roots;
myRootsReversed = new TObjectIntHashMap<>();
for (int i = 0; i < roots.size(); i++) {
myRootsReversed.put(roots.get(i), i);
}
}
@Override
public void save(@NotNull DataOutput out, CommitId value) throws IOException {
((HashImpl)value.getHash()).write(out);
out.writeInt(myRootsReversed.get(value.getRoot()));
}
@Override
public CommitId read(@NotNull DataInput in) throws IOException {
Hash hash = HashImpl.read(in);
VirtualFile root = myRoots.get(in.readInt());
if (root == null) return null;
return new CommitId(hash, root);
}
@Override
public int getHashCode(CommitId value) {
return value.hashCode();
}
@Override
public boolean isEqual(CommitId val1, CommitId val2) {
return val1.equals(val2);
}
}
private static class EmptyLogStorage implements VcsLogStorage {
@Override
public int getCommitIndex(@NotNull Hash hash, @NotNull VirtualFile root) {
return 0;
}
@NotNull
@Override
public CommitId getCommitId(int commitIndex) {
throw new UnsupportedOperationException("Illegal access to empty hash map by index " + commitIndex);
}
@Override
public boolean containsCommit(@NotNull CommitId id) {
return false;
}
@Override
public void iterateCommits(@NotNull Predicate<? super CommitId> consumer) {
}
@Override
public int getRefIndex(@NotNull VcsRef ref) {
return 0;
}
@Nullable
@Override
public VcsRef getVcsRef(int refIndex) {
throw new UnsupportedOperationException("Illegal access to empty ref map by index " + refIndex);
}
@Override
public void flush() {
}
}
private static class VcsRefKeyDescriptor implements KeyDescriptor<VcsRef> {
@NotNull private final Map<VirtualFile, VcsLogProvider> myLogProviders;
@NotNull private final KeyDescriptor<CommitId> myCommitIdKeyDescriptor;
VcsRefKeyDescriptor(@NotNull Map<VirtualFile, VcsLogProvider> logProviders,
@NotNull KeyDescriptor<CommitId> commitIdKeyDescriptor) {
myLogProviders = logProviders;
myCommitIdKeyDescriptor = commitIdKeyDescriptor;
}
@Override
public int getHashCode(@NotNull VcsRef value) {
return value.hashCode();
}
@Override
public boolean isEqual(@NotNull VcsRef val1, @NotNull VcsRef val2) {
return val1.equals(val2);
}
@Override
public void save(@NotNull DataOutput out, @NotNull VcsRef value) throws IOException {
myCommitIdKeyDescriptor.save(out, new CommitId(value.getCommitHash(), value.getRoot()));
IOUtil.writeUTF(out, value.getName());
myLogProviders.get(value.getRoot()).getReferenceManager().serialize(out, value.getType());
}
@Override
public VcsRef read(@NotNull DataInput in) throws IOException {
CommitId commitId = myCommitIdKeyDescriptor.read(in);
if (commitId == null) throw new IOException("Can not read commit id for reference");
String name = IOUtil.readUTF(in);
VcsRefType type = myLogProviders.get(commitId.getRoot()).getReferenceManager().deserialize(in);
return new VcsRefImpl(commitId.getHash(), name, type, commitId.getRoot());
}
}
private static final class MyPersistentBTreeEnumerator extends PersistentBTreeEnumerator<CommitId> {
MyPersistentBTreeEnumerator(@NotNull StorageId storageId, @NotNull KeyDescriptor<CommitId> commitIdKeyDescriptor) throws IOException {
super(storageId.getStorageFile(STORAGE), commitIdKeyDescriptor, Page.PAGE_SIZE, new StorageLockContext(true, true),
storageId.getVersion());
}
public boolean contains(@NotNull CommitId id) throws IOException {
return tryEnumerate(id) != NULL_ID;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.