answer stringlengths 17 10.2M |
|---|
package api.web.gw2.mapping.v2.wvw.matches;
import api.web.gw2.mapping.core.DateValue;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.MapValue;
import api.web.gw2.mapping.core.SetValue;
import api.web.gw2.mapping.v2.APIv2;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Set;
@APIv2(endpoint = "v2/wvw/matches") // NOI18N.
public interface Match {
/**
* Gets the id of this WvW match.
* @return A {@code String} instance, never {@code null}.
*/
@IdValue(flavor = IdValue.Flavor.STRING)
String getId();
/**
* Gets the start time of this WvW match.
* @return A {@code ZonedDateTime} instance, never {@code null}.
*/
@DateValue
ZonedDateTime getStartTime();
/**
* Gets the end time of this WvW match.
* @return A {@code ZonedDateTime} instance, never {@code null}.
*/
@DateValue
ZonedDateTime getEndTime();
/**
* Gets the scores for this WvW match.
* @return A {@code Map<MatchTeam, Integer>}, never {@code null}, may be empty.
*/
@MapValue
Map<MatchTeam, Integer> getScores();
/**
* Gets the worlds for this WvW match.
* @return A {@code Map<MatchTeam, Integer>}, never {@code null}, may be empty.
*/
@IdValue
@MapValue
Map<MatchTeam, Integer> getWorlds();
/**
* Gets all worlds that are teamed up for this WvW match.
* @return A {@code Map<MatchTeam, Set<Integer>>}, never {@code null}, may be empty.
*/
@IdValue
@MapValue
@SetValue
Map<MatchTeam, Set<Integer>> getAllWorlds();
/**
* Gets the deaths for this WvW match.
* @return A {@code Map<MatchTeam, Integer>}, never {@code null}, may be empty.
*/
@MapValue
Map<MatchTeam, Integer> getDeaths();
/**
* Gets the kills for this WvW match.
* @return A {@code Map<MatchTeam, Integer>}, never {@code null}, may be empty.
*/
@MapValue
Map<MatchTeam, Integer> getKills();
/**
* Gets detailed information about each map during this match.
* @return A non-modifiable {@code Set<MatchMap>}, never {@code null}.
*/
@SetValue
Set<MatchMap> getMaps();
} |
package org.dna.mqtt.moquette.client;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.demux.DemuxingProtocolDecoder;
import org.apache.mina.filter.codec.demux.DemuxingProtocolEncoder;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.dna.mqtt.commons.MessageIDGenerator;
import org.dna.mqtt.moquette.ConnectionException;
import org.dna.mqtt.moquette.MQTTException;
import org.dna.mqtt.moquette.PublishException;
import org.dna.mqtt.moquette.SubscribeException;
import org.dna.mqtt.moquette.proto.ConnAckDecoder;
import org.dna.mqtt.moquette.proto.ConnectEncoder;
import org.dna.mqtt.moquette.proto.DisconnectEncoder;
import org.dna.mqtt.moquette.proto.PingReqEncoder;
import org.dna.mqtt.moquette.proto.PingRespDecoder;
import org.dna.mqtt.moquette.proto.PublishDecoder;
import org.dna.mqtt.moquette.proto.PublishEncoder;
import org.dna.mqtt.moquette.proto.SubAckDecoder;
import org.dna.mqtt.moquette.proto.SubscribeEncoder;
import org.dna.mqtt.moquette.proto.messages.AbstractMessage;
import org.dna.mqtt.moquette.proto.messages.ConnAckMessage;
import org.dna.mqtt.moquette.proto.messages.ConnectMessage;
import org.dna.mqtt.moquette.proto.messages.DisconnectMessage;
import org.dna.mqtt.moquette.proto.messages.MessageIDMessage;
import org.dna.mqtt.moquette.proto.messages.PingReqMessage;
import org.dna.mqtt.moquette.proto.messages.PublishMessage;
import org.dna.mqtt.moquette.proto.messages.SubscribeMessage;
import org.dna.mqtt.moquette.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The API to connect to a MQTT server.
*
* Pass to the constructor the host and port to connect, invoke the connect
* message, invoke publish to send notifications messages, invoke subscribe with
* a callback to be notified when something happen on the desired topic.
*
* NB this class is not thread safe so MUST be used by only one thread at time.
*
* @author andrea
*/
public final class Client {
final static int DEFAULT_RETRIES = 3;
final static int RETRIES_QOS_GT0 = 3;
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
// private static final String HOSTNAME = /*"localhost"*/ "127.0.0.1";
// private static final int PORT = Server.PORT;
private static final long CONNECT_TIMEOUT = 3 * 1000L; // 3 seconds
private static final long SUBACK_TIMEOUT = 4 * 1000L;
private static final int KEEPALIVE_SECS = 3;
private static final int NUM_SCHEDULER_TIMER_THREAD = 1;
private int m_connectRetries = DEFAULT_RETRIES;
private String m_hostname;
private int m_port;
//internal mangement used for conversation with the server
private IoConnector m_connector;
private IoSession m_session;
private CountDownLatch m_connectBarrier;
private CountDownLatch m_subscribeBarrier;
private int m_receivedSubAckMessageID;
private byte m_returnCode;
//TODO synchronize the access
//Refact the da model should be a list of callback for each topic
private Map<String, IPublishCallback> m_subscribersList = new HashMap<String, IPublishCallback>();
private ScheduledExecutorService m_scheduler;
private ScheduledFuture m_pingerHandler;
private String m_macAddress;
private MessageIDGenerator m_messageIDGenerator = new MessageIDGenerator();
/**Maintain the list of in flight messages for QoS > 0*/
// private Set<Integer> m_inflightIDs = new HashSet<Integer>();
private String m_clientID;
final Runnable pingerDeamon = new Runnable() {
public void run() {
LOG.debug("Pingreq sent");
//send a ping req
m_session.write(new PingReqMessage());
}
};
public Client(String host, int port) {
m_hostname = host;
m_port = port;
init();
}
/**
* Constructor in which the user could provide it's own ClientID
*/
public Client(String host, int port, String clientID) {
this(host, port);
m_clientID = clientID;
}
protected void init() {
DemuxingProtocolDecoder decoder = new DemuxingProtocolDecoder();
decoder.addMessageDecoder(new ConnAckDecoder());
decoder.addMessageDecoder(new SubAckDecoder());
decoder.addMessageDecoder(new PublishDecoder());
decoder.addMessageDecoder(new PingRespDecoder());
DemuxingProtocolEncoder encoder = new DemuxingProtocolEncoder();
encoder.addMessageEncoder(ConnectMessage.class, new ConnectEncoder());
encoder.addMessageEncoder(PublishMessage.class, new PublishEncoder());
encoder.addMessageEncoder(SubscribeMessage.class, new SubscribeEncoder());
encoder.addMessageEncoder(DisconnectMessage.class, new DisconnectEncoder());
encoder.addMessageEncoder(PingReqMessage.class, new PingReqEncoder());
m_connector = new NioSocketConnector();
// m_connector.getFilterChain().addLast("logger", new LoggingFilter());
m_connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(encoder, decoder));
m_connector.setHandler(new ClientMQTTHandler(this));
m_connector.getSessionConfig().setReadBufferSize(2048);
m_connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Server.DEFAULT_CONNECT_TIMEOUT);
m_scheduler = Executors.newScheduledThreadPool(NUM_SCHEDULER_TIMER_THREAD);
m_macAddress = readMACAddress();
}
/**
* Connects to the server with clean session set to true, do not maintains
* client topic subscriptions
*/
public void connect() throws MQTTException {
connect(true);
}
public void connect(boolean cleanSession) throws MQTTException {
int retries = 0;
try {
ConnectFuture future = m_connector.connect(new InetSocketAddress(m_hostname, m_port));
LOG.debug("Client waiting to connect to server");
future.awaitUninterruptibly();
m_session = future.getSession();
} catch (RuntimeIoException e) {
LOG.debug("Failed to connect, retry " + retries + " of (" + m_connectRetries + ")", e);
}
if (retries == m_connectRetries) {
throw new MQTTException("Can't connect to the server after " + retries + "retries");
}
m_connectBarrier = new CountDownLatch(1);
//send a message over the session
ConnectMessage connMsg = new ConnectMessage();
connMsg.setKeepAlive(KEEPALIVE_SECS);
if (m_clientID == null) {
m_clientID = generateClientID();
}
connMsg.setClientID(m_clientID);
connMsg.setCleanSession(cleanSession);
m_session.write(connMsg);
//suspend until the server respond with CONN_ACK
boolean unlocked = false;
try {
unlocked = m_connectBarrier.await(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); //TODO parametrize
} catch (InterruptedException ex) {
throw new ConnectionException(ex);
}
//if not arrive into certain limit, raise an error
if (!unlocked) {
throw new ConnectionException("Connection timeout elapsed unless server responded with a CONN_ACK");
}
//also raise an error when CONN_ACK is received with some error code inside
if (m_returnCode != ConnAckMessage.CONNECTION_ACCEPTED) {
String errMsg;
switch (m_returnCode) {
case ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION:
errMsg = "Unacceptable protocol version";
break;
case ConnAckMessage.IDENTIFIER_REJECTED:
errMsg = "Identifier rejected";
break;
case ConnAckMessage.SERVER_UNAVAILABLE:
errMsg = "Server unavailable";
break;
case ConnAckMessage.BAD_USERNAME_OR_PASSWORD:
errMsg = "Bad username or password";
break;
case ConnAckMessage.NOT_AUTHORIZED:
errMsg = "Not authorized";
break;
default:
errMsg = "Not idetified erro code " + m_returnCode;
}
throw new ConnectionException(errMsg);
}
updatePinger();
}
/**
* Publish to the connected server the payload message to the given topic.
* It's admitted to publish a 0 -length payload.
*/
public void publish(String topic, byte[] payload) throws PublishException {
publish(topic, payload, false);
}
public void publish(String topic, byte[] payload, boolean retain) throws PublishException {
PublishMessage msg = new PublishMessage();
msg.setRetainFlag(retain);
msg.setTopicName(topic);
msg.setPayload(payload);
//Untill the server could handle all the Qos levels
msg.setQos(AbstractMessage.QOSType.MOST_ONE);
WriteFuture wf = m_session.write(msg);
try {
wf.await();
} catch (InterruptedException ex) {
LOG.debug(null, ex);
throw new PublishException(ex);
}
Throwable ex = wf.getException();
if (ex != null) {
throw new PublishException(ex);
}
updatePinger();
}
public void subscribe(String topic, IPublishCallback publishCallback) {
LOG.info("subscribe invoked");
SubscribeMessage msg = new SubscribeMessage();
msg.addSubscription(new SubscribeMessage.Couple((byte) AbstractMessage.QOSType.MOST_ONE.ordinal(), topic));
msg.setQos(AbstractMessage.QOSType.LEAST_ONE);
int messageID = m_messageIDGenerator.next();
msg.setMessageID(messageID);
// m_inflightIDs.add(messageID);
register(topic, publishCallback);
boolean unlocked = false; //true when a SUBACK is received
try {
manageSendQoS1(msg);
// for (int retries = 0; retries < RETRIES_QOS_GT0 || !unlocked; retries++) {
// if (retries > 0) {
// msg.setDupFlag(true);
// WriteFuture wf = m_session.write(msg);
// try {
// wf.await();
// } catch (InterruptedException ex) {
// LOG.error(null, ex);
// throw new SubscribeException(ex);
// LOG.info("subscribe message sent");
// Throwable ex = wf.getException();
// if (ex != null) {
// throw new SubscribeException(ex);
// //wait for the SubAck
// m_subscribeBarrier = new CountDownLatch(1);
// //suspend until the server respond with CONN_ACK
// try {
// LOG.info("subscribe waiting for suback");
// unlocked = m_subscribeBarrier.await(SUBACK_TIMEOUT, TimeUnit.MILLISECONDS); //TODO parametrize
// } catch (InterruptedException iex) {
// throw new SubscribeException(iex);
// //if not arrive into certain limit, raise an error
// if (!unlocked) {
// throw new SubscribeException(String.format("Server doesn't replyed with a SUB_ACK after %d replies", RETRIES_QOS_GT0));
// } else {
// //check if message ID match
// if (m_receivedSubAckMessageID != messageID) {
// throw new SubscribeException(String.format("Server replyed with "
// + "a broken MessageID in SUB_ACK, expected %d but received %d",
// messageID, m_receivedSubAckMessageID));
} catch(Throwable ex) {
//in case errors arise, remove the registration because the subscription
// hasn't get well
unregister(topic);
throw new MQTTException(ex);
}
// register(topic, publishCallback);
updatePinger();
//TODO check the ACK messageID
}
private void manageSendQoS1(MessageIDMessage msg) throws Throwable{
int messageID = msg.getMessageID();
boolean unlocked = false;
for (int retries = 0; retries < RETRIES_QOS_GT0 || !unlocked; retries++) {
if (retries > 0) {
msg.setDupFlag(true);
}
WriteFuture wf = m_session.write(msg);
wf.await();
LOG.info("message sent");
Throwable ex = wf.getException();
if (ex != null) {
throw ex;
}
//wait for the SubAck
m_subscribeBarrier = new CountDownLatch(1);
//suspend until the server respond with CONN_ACK
LOG.info("subscribe waiting for suback");
unlocked = m_subscribeBarrier.await(SUBACK_TIMEOUT, TimeUnit.MILLISECONDS); //TODO parametrize
}
//if not arrive into certain limit, raise an error
if (!unlocked) {
throw new SubscribeException(String.format("Server doesn't replyed with a SUB_ACK after %d replies", RETRIES_QOS_GT0));
} else {
//check if message ID match
if (m_receivedSubAckMessageID != messageID) {
throw new SubscribeException(String.format("Server replyed with "
+ "a broken MessageID in SUB_ACK, expected %d but received %d",
messageID, m_receivedSubAckMessageID));
}
}
}
/**
* TODO extract this SPI method in a SPI
*/
protected void connectionAckCallback(byte returnCode) {
LOG.info("connectionAckCallback invoked");
m_returnCode = returnCode;
m_connectBarrier.countDown();
}
protected void subscribeAckCallback(int messageID) {
LOG.info("subscribeAckCallback invoked");
m_subscribeBarrier.countDown();
m_receivedSubAckMessageID = messageID;
}
protected void publishCallback(String topic, byte[] payload) {
IPublishCallback callback = m_subscribersList.get(topic);
if (callback == null) {
String msg = String.format("Can't find any publish callback fr topic %s", topic);
LOG.error(msg);
throw new MQTTException(msg);
}
callback.published(topic, payload);
}
/**
* In the current pinger is not ye executed, then cancel it and schedule
* another by KEEPALIVE_SECS
*/
private void updatePinger() {
if (m_pingerHandler != null) {
m_pingerHandler.cancel(false);
}
m_pingerHandler = m_scheduler.scheduleWithFixedDelay(pingerDeamon, KEEPALIVE_SECS, KEEPALIVE_SECS, TimeUnit.SECONDS);
}
private String readMACAddress() {
try {
NetworkInterface network = NetworkInterface.getNetworkInterfaces().nextElement();
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], ""));
}
return sb.toString();
} catch (Exception ex) {
throw new MQTTException("Can't retrieve host MAC address", ex);
}
}
private String generateClientID() {
double rnd = Math.random();
String id = "Moque" + m_macAddress + Math.round(rnd*1000);
LOG.debug("Generated ClientID " + id);
return id;
}
public void close() {
//stop the pinger
m_pingerHandler.cancel(false);
//send the CLOSE message
m_session.write(new DisconnectMessage());
// wait until the summation is done
m_session.getCloseFuture().awaitUninterruptibly();
// m_connector.dispose();
}
public void shutdown() {
m_connector.dispose();
}
/**
* Used only to re-register the callback with the topic, not to send any
* subscription message to the server, used when a client reconnect to an
* existing session on the server
*/
public void register(String topic, IPublishCallback publishCallback) {
//register the publishCallback in some registry to be notified
m_subscribersList.put(topic, publishCallback);
}
//Remove the registration of the callback from the topic
private void unregister(String topic) {
m_subscribersList.remove(topic);
}
} |
package com.vinexs.eeb.misc;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.vinexs.tool.WebkitCookieManager;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
@SuppressWarnings("unused")
public class EnhancedHttp {
private static final String TAG = "EnhancedHttp";
private static final int METHOD_GET = 0;
private static final int METHOD_POST = 1;
private static final int METHOD_POST_MULTIPART = 2;
private static final String LINE_FEED = "\r\n";
private static final String BOUNDARY = "REQUESTBOUNDARY";
private HttpURLConnection conn = null;
private Context context = null;
private int useMethod = EnhancedHttp.METHOD_GET;
private Boolean noCache = false;
private Boolean allowRedirect = false;
private LinkedHashMap<String, String> requestProperty = new LinkedHashMap<>();
private LinkedHashMap<String, String> data = new LinkedHashMap<>();
private LinkedHashMap<String, File> files = new LinkedHashMap<>();
private int htmlStatusCode;
private String htmlResponse;
public EnhancedHttp(Context context) {
this.context = context;
android.webkit.CookieManager.getInstance().setAcceptCookie(true);
java.net.CookieHandler.setDefault(new WebkitCookieManager(context, null, java.net.CookiePolicy.ACCEPT_ALL));
}
public HttpURLConnection getConnection() {
return conn;
}
public int getStatusCode() {
return htmlStatusCode;
}
public String getHtmlResponse() {
return htmlResponse;
}
public EnhancedHttp setNoCache() {
noCache = true;
return this;
}
public EnhancedHttp setAllowRedirect() {
allowRedirect = true;
return this;
}
public EnhancedHttp setData(String name, String value) {
data.put(name, value);
return this;
}
public EnhancedHttp setData(String name, File file) {
files.put(name, file);
useMethod = EnhancedHttp.METHOD_POST_MULTIPART;
return this;
}
public EnhancedHttp setUserAgent(String agent) {
String userAgent = "Mozilla/5.0(Linux; Android; EEB)";
requestProperty.put("User-Agent", userAgent);
return this;
}
public EnhancedHttp setRequestProperty(String field, String newValue) {
requestProperty.put(field, newValue);
return this;
}
public void get(String url) {
get(url, null);
}
public void get(String url, LinkedHashMap<String, Object> vars, OnResponseListener response) {
for (Map.Entry<String, Object> variable : vars.entrySet()) {
if (!(variable.getValue() instanceof java.io.File)) {
data.put(variable.getKey(), variable.getValue().toString());
}
}
get(url, response);
}
public void get(String url, OnResponseListener response) {
buildConnection(url, response);
}
public void post(String url) {
post(url, null);
}
public void post(String url, LinkedHashMap<String, Object> vars, OnResponseListener response) {
for (Map.Entry<String, Object> variable : vars.entrySet()) {
if (variable.getValue() instanceof java.io.File) {
if (!((File) variable.getValue()).exists()) {
continue;
}
files.put(variable.getKey(), (File) variable.getValue());
useMethod = EnhancedHttp.METHOD_POST_MULTIPART;
} else {
data.put(variable.getKey(), variable.getValue().toString());
}
}
post(url, response);
}
public void post(String url, OnResponseListener response) {
if (useMethod != EnhancedHttp.METHOD_POST_MULTIPART) {
useMethod = EnhancedHttp.METHOD_POST;
}
buildConnection(url, response);
}
public void buildConnection(final String url, final OnResponseListener responseListener) {
new AsyncTask<Object, Integer, String>() {
@Override
protected String doInBackground(Object... params) {
try {
String actionUrl = url;
if (useMethod == EnhancedHttp.METHOD_GET) {
if (!data.isEmpty()) {
actionUrl += ((!url.contains("?")) ? "?" : "&") + getQueryStr();
}
}
URL urlconn = new URL(actionUrl);
if (!actionUrl.startsWith("https:")) {
conn = (HttpURLConnection) urlconn.openConnection();
} else {
conn = (HttpsURLConnection) urlconn.openConnection();
}
conn.setDoInput(responseListener != null);
conn.setInstanceFollowRedirects(allowRedirect);
conn.setUseCaches(!noCache);
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Accept-Encoding", "gzip");
if (requestProperty.size() > 0) {
for (Map.Entry<String, String> request : requestProperty.entrySet()) {
conn.setRequestProperty(request.getKey(), request.getValue());
}
}
switch (useMethod) {
case EnhancedHttp.METHOD_POST_MULTIPART:
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
DataOutputStream multipartOutputStream = new DataOutputStream(conn.getOutputStream());
if (!files.isEmpty()) {
for (Map.Entry<String, File> file : files.entrySet()) {
if (!file.getValue().exists()) {
Log.e(TAG, "File dropped. [" + file.getValue().toString() + "]");
continue;
}
multipartAddFile(multipartOutputStream, file.getKey(), file.getValue());
}
}
if (!data.isEmpty()) {
for (Map.Entry<String, String> var : data.entrySet()) {
multipartAddParam(multipartOutputStream, var.getKey(), var.getValue());
}
}
multipartOutputStream.close();
break;
case EnhancedHttp.METHOD_POST:
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (!data.isEmpty()) {
byte[] postData = getQueryStr().getBytes("UTF-8");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
postOutputStream.write(postData);
postOutputStream.close();
}
break;
case EnhancedHttp.METHOD_GET:
default:
break;
}
htmlStatusCode = conn.getResponseCode();
if (htmlStatusCode != HttpURLConnection.HTTP_OK) {
conn.disconnect();
return null;
}
StringBuilder stringBuilder = new StringBuilder();
if (responseListener != null) {
String line;
InputStream inputStream =
(conn instanceof HttpsURLConnection && "gzip".equals(conn.getContentEncoding())) ?
new GZIPInputStream(conn.getInputStream()) : conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
reader.close();
}
conn.disconnect();
htmlResponse = stringBuilder.toString();
return htmlResponse;
} catch (Exception e) {
e.printStackTrace();
try {
htmlStatusCode = conn.getResponseCode();
conn.disconnect();
} catch (Exception ignored) {
}
return null;
}
}
@Override
protected void onPostExecute(String htmlResponse) {
if (responseListener != null) {
if (htmlStatusCode == HttpURLConnection.HTTP_OK) {
responseListener.onSuccess(context, htmlResponse);
} else {
Log.e("EnhancedHttp", conn.getURL().toString() + " response error " + htmlStatusCode);
responseListener.onError(context, htmlStatusCode);
}
}
}
}.execute();
}
public void multipartAddParam(DataOutputStream outputStream, String name, String value) throws IOException {
outputStream.writeBytes("--" + BOUNDARY + LINE_FEED);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + LINE_FEED);
outputStream.writeBytes("Content-Type: text/plain; chart=utf8" + LINE_FEED);
outputStream.writeBytes(LINE_FEED);
outputStream.writeBytes(value + LINE_FEED);
outputStream.writeBytes("--" + BOUNDARY + LINE_FEED + LINE_FEED);
}
public void multipartAddFile(DataOutputStream outputStream, String name, File file) throws IOException {
String fileName = file.getName();
outputStream.writeBytes("--" + BOUNDARY + LINE_FEED);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\";filename=\"" + fileName + "\"" + LINE_FEED);
outputStream.writeBytes("Content-Type: " + HttpURLConnection.guessContentTypeFromName(fileName) + LINE_FEED);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + LINE_FEED);
outputStream.writeBytes(LINE_FEED);
byte[] fileByte = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
//noinspection ResultOfMethodCallIgnored
fileInputStream.read(fileByte);
fileInputStream.close();
outputStream.write(fileByte);
outputStream.writeBytes(LINE_FEED);
outputStream.writeBytes("--" + BOUNDARY + LINE_FEED + LINE_FEED);
}
public String getQueryStr() {
return getQueryStr(data);
}
public String getQueryStr(LinkedHashMap<String, String> params) {
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
try {
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
} catch (UnsupportedEncodingException e) {
Log.e("EnhancedHttp", "Variable [" + param.getKey() + "] fail to encode.");
}
}
return postData.toString();
}
public interface OnResponseListener {
void onSuccess(Context context, String response);
void onError(Context context, int stateCode);
}
} |
package io.permazen.kv.raft;
import com.google.common.base.Preconditions;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
/**
* One shot timer that {@linkplain RaftKVDatabase#requestService requests} a {@link Service} on expiration.
*
* <p>
* This implementation avoids any race conditions between scheduling, firing, and cancelling.
*/
class Timer {
private final RaftKVDatabase raft;
private final Logger log;
private final String name;
private final Service service;
private ScheduledFuture<?> future;
private PendingTimeout pendingTimeout; // non-null IFF timeout has not been handled yet
private Timestamp timeoutDeadline;
Timer(final RaftKVDatabase raft, final String name, final Service service) {
assert raft != null;
assert name != null;
assert service != null;
this.raft = raft;
this.log = this.raft.logger;
this.name = name;
this.service = service;
}
public void cancel() {
// Sanity check
assert Thread.holdsLock(this.raft);
// Cancel existing timer, if any
if (this.future != null) {
this.future.cancel(false);
this.future = null;
}
// Ensure the previously scheduled action does nothing if case we lose the cancel() race condition
this.pendingTimeout = null;
this.timeoutDeadline = null;
}
public void timeoutAfter(int delay) {
// Sanity check
assert Thread.holdsLock(this.raft);
Preconditions.checkArgument(delay >= 0, "delay < 0");
// Cancel existing timeout action, if any
this.cancel();
assert this.future == null;
assert this.pendingTimeout == null;
assert this.timeoutDeadline == null;
// Reschedule new timeout action
this.timeoutDeadline = new Timestamp().offset(delay);
if (this.log.isTraceEnabled()) {
this.raft.trace("rescheduling " + this.name + " for " + this.timeoutDeadline
+ " (" + delay + "ms from now)");
}
Preconditions.checkArgument(!this.timeoutDeadline.isRolloverDanger(), "delay too large");
this.pendingTimeout = new PendingTimeout();
try {
this.future = this.raft.serviceExecutor.schedule(this.pendingTimeout, delay, TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException e) {
if (!this.raft.shuttingDown)
this.raft.warn("can't restart timer", e);
}
}
/**
* Force timer to expire immediately.
*/
public void timeoutNow() {
this.timeoutAfter(0);
}
/**
* Get the deadline.
*
* @return timer deadline, or null if not running
*/
public Timestamp getDeadline() {
return this.timeoutDeadline;
}
/**
* Determine if this timer has expired and requires service handling, and reset it if so.
*
* <p>
* If this timer is not running, has not yet expired, or has previously expired and this method was already
* thereafter invoked, false is returned. Otherwise, true is returned, this timer is {@link #cancel}ed (if necessary),
* and the caller is expected to handle the implied service need.
*
* @return true if timer needs handling, false otherwise
*/
public boolean pollForTimeout() {
// Sanity check
assert Thread.holdsLock(this.raft);
// Has timer expired?
if (this.pendingTimeout == null || !this.timeoutDeadline.hasOccurred())
return false;
// Yes, timer requires service
if (Timer.this.log.isTraceEnabled())
this.raft.trace(Timer.this.name + " expired " + -this.timeoutDeadline.offsetFromNow() + "ms ago");
this.cancel();
return true;
}
/**
* Determine if this timer is running, i.e., will expire or has expired but
* {@link #pollForTimeout} has not been invoked yet.
*/
public boolean isRunning() {
return this.pendingTimeout != null;
}
// PendingTimeout
private class PendingTimeout implements Runnable {
@Override
public void run() {
synchronized (Timer.this.raft) {
// Avoid cancel() race condition
if (Timer.this.pendingTimeout != this)
return;
// Trigger service
Timer.this.raft.requestService(Timer.this.service);
}
}
}
} |
package herencia;
public class Padre {
private String clase;
private String tipo;
public String getClase() {
return clase;
}
public void setClase(String clase) {
this.clase = clase;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
//al crear un constructor con parametros desaparece el constructor por defecto
public Padre(String clase, String tipo){
setClase(clase);
setTipo(tipo);
}
} |
package com.jme3.scene.plugins.ogre;
import com.jme3.animation.AnimControl;
import com.jme3.animation.BoneAnimation;
import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetLoader;
import com.jme3.asset.AssetManager;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.material.Material;
import com.jme3.material.MaterialList;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap;
import com.jme3.util.IntMap.Entry;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import static com.jme3.util.xml.SAXUtil.*;
/**
* Loads Ogre3D mesh.xml files.
*/
public class MeshLoader extends DefaultHandler implements AssetLoader {
private static final Logger logger = Logger.getLogger(MeshLoader.class.getName());
public static boolean AUTO_INTERLEAVE = true;
public static boolean HARDWARE_SKINNING = false;
private String meshName;
private String folderName;
private AssetManager assetManager;
private MaterialList materialList;
private ShortBuffer sb;
private IntBuffer ib;
private FloatBuffer fb;
private VertexBuffer vb;
private Mesh mesh;
private Geometry geom;
private Mesh sharedmesh;
private Geometry sharedgeom;
private int geomIdx = 0;
private int texCoordIdx = 0;
private static volatile int nodeIdx = 0;
private String ignoreUntilEnd = null;
private boolean bigindices = false;
private int vertCount;
private int triCount;
private List<Geometry> geoms = new ArrayList<Geometry>();
private List<Boolean> usesSharedGeom = new ArrayList<Boolean>();
private IntMap<List<VertexBuffer>> lodLevels = new IntMap<List<VertexBuffer>>();
private AnimData animData;
private ByteBuffer indicesData;
private FloatBuffer weightsFloatData;
public MeshLoader(){
super();
}
@Override
public void startDocument() {
geoms.clear();
usesSharedGeom.clear();
lodLevels.clear();
sb = null;
ib = null;
fb = null;
vb = null;
mesh = null;
geom = null;
sharedgeom = null;
sharedmesh = null;
vertCount = 0;
triCount = 0;
geomIdx = 0;
texCoordIdx = 0;
nodeIdx = 0;
ignoreUntilEnd = null;
animData = null;
indicesData = null;
weightsFloatData = null;
}
@Override
public void endDocument() {
}
private void pushFace(String v1, String v2, String v3) throws SAXException{
int i1 = parseInt(v1);
// TODO: fan/strip support
int i2 = parseInt(v2);
int i3 = parseInt(v3);
if (ib != null){
ib.put(i1).put(i2).put(i3);
}else{
sb.put((short)i1).put((short)i2).put((short)i3);
}
}
private void startFaces(String count) throws SAXException{
int numFaces = parseInt(count);
int numIndices;
if (mesh.getMode() == Mesh.Mode.Triangles){
//mesh.setTriangleCount(numFaces);
numIndices = numFaces * 3;
}else{
throw new SAXException("Triangle strip or fan not supported!");
}
int numVerts;
if (usesSharedGeom.size() > 0 && usesSharedGeom.get(geoms.size()-1)){
// sharedgeom.getMesh().updateCounts();
numVerts = sharedmesh.getVertexCount();
}else{
// mesh.updateCounts();
numVerts = mesh.getVertexCount();
}
vb = new VertexBuffer(VertexBuffer.Type.Index);
if (!bigindices){
sb = BufferUtils.createShortBuffer(numIndices);
ib = null;
vb.setupData(Usage.Static, 3, Format.UnsignedShort, sb);
}else{
ib = BufferUtils.createIntBuffer(numIndices);
sb = null;
vb.setupData(Usage.Static, 3, Format.UnsignedInt, ib);
}
mesh.setBuffer(vb);
}
private void applyMaterial(Geometry geom, String matName){
Material mat = null;
if (matName.endsWith(".j3m")){
// load as native jme3 material instance
mat = assetManager.loadMaterial(matName);
}else{
if (materialList != null){
mat = materialList.get(matName);
}
if (mat == null){
logger.log(Level.WARNING, "Material {0} not found. Applying default material", matName);
mat = (Material) assetManager.loadAsset(new AssetKey("Common/Materials/RedColor.j3m"));
}
}
if (mat == null)
throw new RuntimeException("Cannot locate material named " + matName);
if (mat.isTransparent())
geom.setQueueBucket(Bucket.Transparent);
// else
// geom.setShadowMode(ShadowMode.CastAndReceive);
// if (mat.isReceivesShadows())
geom.setMaterial(mat);
}
private void startMesh(String matName, String usesharedvertices, String use32bitIndices, String opType) throws SAXException{
mesh = new Mesh();
if (opType == null || opType.equals("triangle_list")){
mesh.setMode(Mesh.Mode.Triangles);
}else if (opType.equals("triangle_strip")){
mesh.setMode(Mesh.Mode.TriangleStrip);
}else if (opType.equals("triangle_fan")){
mesh.setMode(Mesh.Mode.TriangleFan);
}
bigindices = parseBool(use32bitIndices, false);
boolean sharedverts = parseBool(usesharedvertices, false);
if (sharedverts){
usesSharedGeom.add(true);
// import vertexbuffers from shared geom
IntMap<VertexBuffer> sharedBufs = sharedmesh.getBuffers();
for (Entry<VertexBuffer> entry : sharedBufs){
mesh.setBuffer(entry.getValue());
}
// this mesh is shared!
}else{
usesSharedGeom.add(false);
}
if (meshName == null)
geom = new Geometry("OgreSubmesh-"+(++geomIdx), mesh);
else
geom = new Geometry(meshName+"-geom-"+(++geomIdx), mesh);
applyMaterial(geom, matName);
geoms.add(geom);
}
private void startSharedGeom(String vertexcount) throws SAXException{
sharedmesh = new Mesh();
vertCount = parseInt(vertexcount);
// sharedmesh.setVertexCount(vertCount);
if (meshName == null)
sharedgeom = new Geometry("Ogre-SharedGeom", sharedmesh);
else
sharedgeom = new Geometry(meshName+"-sharedgeom", sharedmesh);
sharedgeom.setCullHint(CullHint.Always);
geoms.add(sharedgeom);
usesSharedGeom.add(false); // shared geometry doesnt use shared geometry (?)
geom = sharedgeom;
mesh = sharedmesh;
}
private void startGeometry(String vertexcount) throws SAXException{
vertCount = parseInt(vertexcount);
// mesh.setVertexCount(vertCount);
}
/**
* Normalizes weights if needed and finds largest amount of weights used
* for all vertices in the buffer.
*/
private void endBoneAssigns(){
if (mesh != sharedmesh && usesSharedGeom.get(geoms.size() - 1)){
return;
}
//int vertCount = mesh.getVertexCount();
int maxWeightsPerVert = 0;
weightsFloatData.rewind();
for (int v = 0; v < vertCount; v++){
float w0 = weightsFloatData.get(),
w1 = weightsFloatData.get(),
w2 = weightsFloatData.get(),
w3 = weightsFloatData.get();
if (w3 != 0){
maxWeightsPerVert = Math.max(maxWeightsPerVert, 4);
}else if (w2 != 0){
maxWeightsPerVert = Math.max(maxWeightsPerVert, 3);
}else if (w1 != 0){
maxWeightsPerVert = Math.max(maxWeightsPerVert, 2);
}else if (w0 != 0){
maxWeightsPerVert = Math.max(maxWeightsPerVert, 1);
}
float sum = w0 + w1 + w2 + w3;
if (sum != 1f){
weightsFloatData.position(weightsFloatData.position()-4);
// compute new vals based on sum
float sumToB = 1f / sum;
weightsFloatData.put( w0 * sumToB );
weightsFloatData.put( w1 * sumToB );
weightsFloatData.put( w2 * sumToB );
weightsFloatData.put( w3 * sumToB );
}
}
weightsFloatData.rewind();
weightsFloatData = null;
indicesData = null;
mesh.setMaxNumWeights(maxWeightsPerVert);
}
private void startBoneAssigns(){
if (mesh != sharedmesh && usesSharedGeom.get(geoms.size() - 1)){
// will use bone assignments from shared mesh (?)
return;
}
// current mesh will have bone assigns
//int vertCount = mesh.getVertexCount();
// each vertex has
// - 4 bone weights
// - 4 bone indices
if (HARDWARE_SKINNING){
weightsFloatData = BufferUtils.createFloatBuffer(vertCount * 4);
indicesData = BufferUtils.createByteBuffer(vertCount * 4);
}else{
// create array-backed buffers if software skinning for access speed
weightsFloatData = FloatBuffer.allocate(vertCount * 4);
indicesData = ByteBuffer.allocate(vertCount * 4);
}
VertexBuffer weights = new VertexBuffer(Type.BoneWeight);
VertexBuffer indices = new VertexBuffer(Type.BoneIndex);
Usage usage = HARDWARE_SKINNING ? Usage.Static : Usage.CpuOnly;
weights.setupData(usage, 4, Format.Float, weightsFloatData);
indices.setupData(usage, 4, Format.UnsignedByte, indicesData);
mesh.setBuffer(weights);
mesh.setBuffer(indices);
}
private void startVertexBuffer(Attributes attribs) throws SAXException{
if (parseBool(attribs.getValue("positions"), false)){
vb = new VertexBuffer(Type.Position);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("normals"), false)){
vb = new VertexBuffer(Type.Normal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("colours_diffuse"), false)){
vb = new VertexBuffer(Type.Color);
fb = BufferUtils.createFloatBuffer(vertCount * 4);
vb.setupData(Usage.Static, 4, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("tangents"), false)){
int dimensions = parseInt(attribs.getValue("tangent_dimensions"), 3);
vb = new VertexBuffer(Type.Tangent);
fb = BufferUtils.createFloatBuffer(vertCount * dimensions);
vb.setupData(Usage.Static, dimensions, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("binormals"), false)){
vb = new VertexBuffer(Type.Binormal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
int texCoords = parseInt(attribs.getValue("texture_coords"), 0);
for (int i = 0; i < texCoords; i++){
int dims = parseInt(attribs.getValue("texture_coord_dimensions_" + i), 2);
if (dims < 1 || dims > 4)
throw new SAXException("Texture coord dimensions must be 1 <= dims <= 4");
if (i >= 2)
throw new SAXException("More than 2 texture coordinates not supported");
if (i == 0){
vb = new VertexBuffer(Type.TexCoord);
}else{
vb = new VertexBuffer(Type.TexCoord2);
}
fb = BufferUtils.createFloatBuffer(vertCount * dims);
vb.setupData(Usage.Static, dims, Format.Float, fb);
mesh.setBuffer(vb);
}
}
private void startVertex(){
texCoordIdx = 0;
}
private void pushAttrib(Type type, Attributes attribs) throws SAXException{
try {
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(type).getData();
buf.put(parseFloat(attribs.getValue("x")))
.put(parseFloat(attribs.getValue("y")))
.put(parseFloat(attribs.getValue("z")));
} catch (Exception ex){
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTangent(Attributes attribs) throws SAXException{
try {
VertexBuffer tangentBuf = mesh.getBuffer(Type.Tangent);
FloatBuffer buf = (FloatBuffer) tangentBuf.getData();
buf.put(parseFloat(attribs.getValue("x")))
.put(parseFloat(attribs.getValue("y")))
.put(parseFloat(attribs.getValue("z")));
if (tangentBuf.getNumComponents() == 4){
buf.put(parseFloat(attribs.getValue("w")));
}
} catch (Exception ex){
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTexCoord(Attributes attribs) throws SAXException{
if (texCoordIdx >= 1)
return; // TODO: More than 2 texcoords
Type type = texCoordIdx == 0 ? Type.TexCoord : Type.TexCoord2;
VertexBuffer tcvb = mesh.getBuffer(type);
FloatBuffer buf = (FloatBuffer) tcvb.getData();
buf.put(parseFloat(attribs.getValue("u")));
if (tcvb.getNumComponents() >= 2){
buf.put(parseFloat(attribs.getValue("v")));
if (tcvb.getNumComponents() >= 3){
buf.put(parseFloat(attribs.getValue("w")));
if (tcvb.getNumComponents() == 4){
buf.put(parseFloat(attribs.getValue("x")));
}
}
}
texCoordIdx++;
}
private void pushColor(Attributes attribs) throws SAXException{
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(Type.Color).getData();
String value = parseString(attribs.getValue("value"));
String[] vals = value.split(" ");
if (vals.length != 3 && vals.length != 4)
throw new SAXException("Color value must contain 3 or 4 components");
ColorRGBA color = new ColorRGBA();
color.r = parseFloat(vals[0]);
color.g = parseFloat(vals[1]);
color.b = parseFloat(vals[2]);
if (vals.length == 3)
color.a = 1f;
else
color.a = parseFloat(vals[3]);
buf.put(color.r).put(color.g).put(color.b).put(color.a);
}
private void startLodFaceList(String submeshindex, String numfaces){
int index = Integer.parseInt(submeshindex);
int faceCount = Integer.parseInt(numfaces);
vb = new VertexBuffer(VertexBuffer.Type.Index);
sb = BufferUtils.createShortBuffer(faceCount * 3);
ib = null;
vb.setupData(Usage.Static, 3, Format.UnsignedShort, sb);
List<VertexBuffer> levels = lodLevels.get(index);
if (levels == null){
levels = new ArrayList<VertexBuffer>();
Mesh submesh = geoms.get(index).getMesh();
levels.add(submesh.getBuffer(Type.Index));
lodLevels.put(index, levels);
}
levels.add(vb);
}
private void startLevelOfDetail(String numlevels){
// numLevels = Integer.parseInt(numlevels);
}
private void endLevelOfDetail(){
// set the lod data for each mesh
for (Entry<List<VertexBuffer>> entry : lodLevels){
Mesh m = geoms.get(entry.getKey()).getMesh();
List<VertexBuffer> levels = entry.getValue();
VertexBuffer[] levelArray = new VertexBuffer[levels.size()];
levels.toArray(levelArray);
m.setLodLevels(levelArray);
}
}
private void startLodGenerated(String depthsqr){
// dist = Float.parseFloat(depthsqr);
}
private void pushBoneAssign(String vertIndex, String boneIndex, String weight) throws SAXException{
int vert = parseInt(vertIndex);
float w = parseFloat(weight);
byte bone = (byte) parseInt(boneIndex);
assert bone >= 0;
assert vert >= 0 && vert < mesh.getVertexCount();
int i;
// see which weights are unused for a given bone
for (i = vert * 4; i < vert * 4 + 4; i++){
float v = weightsFloatData.get(i);
if (v == 0)
break;
}
weightsFloatData.put(i, w);
indicesData.put(i, bone);
}
private void startSkeleton(String name){
animData = (AnimData) assetManager.loadAsset(folderName + name + ".xml");
//TODO:workaround for meshxml / mesh.xml
if(animData==null)
animData = (AnimData) assetManager.loadAsset(folderName + name + "xml");
}
private void startSubmeshName(String indexStr, String nameStr){
int index = Integer.parseInt(indexStr);
geoms.get(index).setName(nameStr);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attribs) throws SAXException{
if (ignoreUntilEnd != null)
return;
if (qName.equals("texcoord")){
pushTexCoord(attribs);
}else if (qName.equals("vertexboneassignment")){
pushBoneAssign(attribs.getValue("vertexindex"),
attribs.getValue("boneindex"),
attribs.getValue("weight"));
}else if (qName.equals("face")){
pushFace(attribs.getValue("v1"),
attribs.getValue("v2"),
attribs.getValue("v3"));
}else if (qName.equals("position")){
pushAttrib(Type.Position, attribs);
}else if (qName.equals("normal")){
pushAttrib(Type.Normal, attribs);
}else if (qName.equals("tangent")){
pushTangent(attribs);
}else if (qName.equals("binormal")){
pushAttrib(Type.Binormal, attribs);
}else if (qName.equals("colour_diffuse")){
pushColor(attribs);
}else if (qName.equals("vertex")){
startVertex();
}else if (qName.equals("faces")){
startFaces(attribs.getValue("count"));
}else if (qName.equals("geometry")){
String count = attribs.getValue("vertexcount");
if (count == null)
count = attribs.getValue("count");
startGeometry(count);
}else if (qName.equals("vertexbuffer")){
startVertexBuffer(attribs);
}else if (qName.equals("lodfacelist")){
startLodFaceList(attribs.getValue("submeshindex"),
attribs.getValue("numfaces"));
}else if (qName.equals("lodgenerated")){
startLodGenerated(attribs.getValue("fromdepthsquared"));
}else if (qName.equals("levelofdetail")){
startLevelOfDetail(attribs.getValue("numlevels"));
}else if (qName.equals("boneassignments")){
startBoneAssigns();
}else if (qName.equals("submesh")){
startMesh(attribs.getValue("material"),
attribs.getValue("usesharedvertices"),
attribs.getValue("use32bitindexes"),
attribs.getValue("operationtype"));
}else if (qName.equals("sharedgeometry")){
String count = attribs.getValue("vertexcount");
if (count == null)
count = attribs.getValue("count");
if (count != null && !count.equals("0"))
startSharedGeom(count);
}else if (qName.equals("submeshes")){
}else if (qName.equals("skeletonlink")){
startSkeleton(attribs.getValue("name"));
}else if (qName.equals("submeshname")){
startSubmeshName(attribs.getValue("index"), attribs.getValue("name"));
}else if (qName.equals("mesh")){
}else{
logger.log(Level.WARNING, "Unknown tag: {0}. Ignoring.", qName);
ignoreUntilEnd = qName;
}
}
@Override
public void endElement(String uri, String name, String qName) {
if (ignoreUntilEnd != null){
if (ignoreUntilEnd.equals(qName))
ignoreUntilEnd = null;
return;
}
if (qName.equals("submesh")){
bigindices = false;
geom = null;
mesh = null;
}else if (qName.equals("submeshes")){
// IMPORTANT: restore sharedgeoemtry, for use with shared boneweights
geom = sharedgeom;
mesh = sharedmesh;
}else if (qName.equals("faces")){
if (ib != null)
ib.flip();
else
sb.flip();
vb = null;
ib = null;
sb = null;
}else if (qName.equals("vertexbuffer")){
fb = null;
vb = null;
}else if (qName.equals("geometry")
|| qName.equals("sharedgeometry")){
// finish writing to buffers
IntMap<VertexBuffer> bufs = mesh.getBuffers();
for (Entry<VertexBuffer> entry : bufs){
Buffer data = entry.getValue().getData();
if (data.position() != 0)
data.flip();
}
mesh.updateBound();
mesh.setStatic();
if (qName.equals("sharedgeometry")){
geom = null;
mesh = null;
}
}else if (qName.equals("lodfacelist")){
sb.flip();
vb = null;
sb = null;
}else if (qName.equals("levelofdetail")){
endLevelOfDetail();
}else if (qName.equals("boneassignments")){
endBoneAssigns();
}
}
@Override
public void characters(char ch[], int start, int length) {
}
private void createBindPose(Mesh mesh){
VertexBuffer pos = mesh.getBuffer(Type.Position);
if (pos == null || mesh.getBuffer(Type.BoneIndex) == null){
// ignore, this mesh doesn't have positional data
// or it doesn't have bone-vertex assignments, so its not animated
return;
}
VertexBuffer bindPos = new VertexBuffer(Type.BindPosePosition);
bindPos.setupData(Usage.CpuOnly,
3,
Format.Float,
BufferUtils.clone(pos.getData()));
mesh.setBuffer(bindPos);
// XXX: note that this method also sets stream mode
// so that animation is faster. this is not needed for hardware skinning
pos.setUsage(Usage.Stream);
VertexBuffer norm = mesh.getBuffer(Type.Normal);
if (norm != null){
VertexBuffer bindNorm = new VertexBuffer(Type.BindPoseNormal);
bindNorm.setupData(Usage.CpuOnly,
3,
Format.Float,
BufferUtils.clone(norm.getData()));
mesh.setBuffer(bindNorm);
norm.setUsage(Usage.Stream);
}
}
private Node compileModel(){
String nodeName;
if (meshName == null)
nodeName = "OgreMesh"+(++nodeIdx);
else
nodeName = meshName+"-ogremesh";
Node model = new Node(nodeName);
if (animData != null){
ArrayList<Mesh> newMeshes = new ArrayList<Mesh>(geoms.size());
// generate bind pose for mesh and add to skin-list
// ONLY if not using shared geometry
// This includes the shared geoemtry itself actually
for (int i = 0; i < geoms.size(); i++){
Geometry g = geoms.get(i);
Mesh m = geoms.get(i).getMesh();
boolean useShared = usesSharedGeom.get(i);
// create bind pose
if (!useShared){
createBindPose(m);
newMeshes.add(m);
}else{
VertexBuffer bindPos = sharedmesh.getBuffer(Type.BindPosePosition);
VertexBuffer bindNorm = sharedmesh.getBuffer(Type.BindPoseNormal);
VertexBuffer boneIndex = sharedmesh.getBuffer(Type.BoneIndex);
VertexBuffer boneWeight = sharedmesh.getBuffer(Type.BoneWeight);
if (bindPos != null)
m.setBuffer(bindPos);
if (bindNorm != null)
m.setBuffer(bindNorm);
if (boneIndex != null)
m.setBuffer(boneIndex);
if (boneWeight != null)
m.setBuffer(boneWeight);
}
}
Mesh[] meshes = new Mesh[newMeshes.size()];
for (int i = 0; i < meshes.length; i++)
meshes[i] = newMeshes.get(i);
HashMap<String, BoneAnimation> anims = new HashMap<String, BoneAnimation>();
ArrayList<BoneAnimation> animList = animData.anims;
for (int i = 0; i < animList.size(); i++){
BoneAnimation anim = animList.get(i);
anims.put(anim.getName(), anim);
}
AnimControl ctrl = new AnimControl(model,
meshes,
animData.skeleton);
ctrl.setAnimations(anims);
model.addControl(ctrl);
}
for (int i = 0; i < geoms.size(); i++){
Geometry g = geoms.get(i);
Mesh m = g.getMesh();
if (sharedmesh != null && usesSharedGeom.get(i)){
m.setBound(sharedmesh.getBound().clone());
}
model.attachChild(geoms.get(i));
}
return model;
}
public Object load(AssetInfo info) throws IOException {
try{
AssetKey key = info.getKey();
meshName = key.getName();
folderName = key.getFolder();
String ext = key.getExtension();
meshName = meshName.substring(0, meshName.length() - ext.length() - 1);
if (folderName != null && folderName.length() > 0){
meshName = meshName.substring(folderName.length());
}
assetManager = info.getManager();
OgreMeshKey meshKey = null;
if (key instanceof OgreMeshKey){
meshKey = (OgreMeshKey) key;
materialList = meshKey.getMaterialList();
}else{
try {
materialList = (MaterialList) assetManager.loadAsset(folderName + meshName + ".material");
} catch (AssetNotFoundException e) {
logger.log(Level.WARNING, "Cannot locate {0}{1}.material for model {2}{3}.{4}", new Object[]{folderName, meshName, folderName, meshName, ext});
}
}
XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(this);
xr.setErrorHandler(this);
InputStreamReader r = new InputStreamReader(info.openStream());
xr.parse(new InputSource(r));
r.close();
return compileModel();
}catch (SAXException ex){
IOException ioEx = new IOException("Error while parsing Ogre3D mesh.xml");
ioEx.initCause(ex);
throw ioEx;
}
}
} |
package net.katsuster.ememu.generic;
/**
* 32bit CPU
*
* CPU
*
*/
public class Stage {
private CPU32 core;
/**
* CPU
*
* @param c CPU
*/
public Stage(CPU32 c) {
core = c;
}
/**
* CPU
*
* @return CPU
*/
public CPU32 getCore() {
return core;
}
/**
*
*
* 32
* 64
*
* @param addr
* @param len
* @return true false
*/
public boolean tryRead_a32(int addr, int len) {
return getCore().tryRead_a32(addr, len);
}
/**
* 8
*
* 32
* 64
*
* @param addr
* @return
*/
public byte read8_a32(int addr) {
return getCore().read8_a32(addr);
}
/**
* 16
*
* 32
* 64
*
* @param addr
* @return
*/
public short read16_a32(int addr) {
return getCore().read16_a32(addr);
}
/**
* 32
*
* 32
* 64
*
* @param addr
* @return
*/
public int read32_a32(int addr) {
return getCore().read32_a32(addr);
}
/**
* 64
*
* 32
* 64
*
* @param addr
* @return
*/
public long read64_a32(int addr) {
return getCore().read64_a32(addr);
}
/**
*
*
* 32
* 64
*
* @param addr
* @param len
* @return true false
*/
public boolean tryWrite_a32(int addr, int len) {
return getCore().tryWrite_a32(addr, len);
}
/**
* 8
*
* 32
* 64
*
* @param addr
* @param data
*/
public void write8_a32(int addr, byte data) {
getCore().write8_a32(addr, data);
}
/**
* 16
*
* 32
* 64
*
* @param addr
* @param data
*/
public void write16_a32(int addr, short data) {
getCore().write16_a32(addr, data);
}
/**
* 32
*
* 32
* 64
*
* @param addr
* @param data
*/
public void write32_a32(int addr, int data) {
getCore().write32_a32(addr, data);
}
/**
* 64
*
* 32
* 64
*
* @param addr
* @param data
*/
public void write64_a32(int addr, long data) {
getCore().write64_a32(addr, data);
}
/**
*
*
* @param inst ARM
* @param operation
* @param operand
*/
public void printDisasm(Inst32 inst, String operation, String operand) {
getCore().printDisasm(inst, operation, operand);
}
/**
* PC
*
* @return PC
*/
public int getPC() {
return getCore().getPC();
}
/**
* PC
*
* @param val PC
*/
public void setPC(int val) {
getCore().setPC(val);
}
/**
* PC
*
* PC
*
* @param inst
*/
public void nextPC(Inst32 inst) {
getCore().nextPC(inst);
}
/**
*
*
* PC +
* PC
*
* @param val
*/
public void jumpRel(int val) {
getCore().jumpRel(val);
}
/**
* Rn
*
* @param n
* @return
*/
public int getReg(int n) {
return getCore().getReg(n);
}
/**
* Rn
*
* @param n
* @param val
*/
public void setReg(int n, int val) {
getCore().setReg(n, val);
}
/**
* Rn
*
* @param n
* @return
*/
public int getRegRaw(int n) {
return getCore().getRegRaw(n);
}
/**
* Rn
*
* @param n
* @param val
*/
public void setRegRaw(int n, int val) {
getCore().setRegRaw(n, val);
}
/**
* Rn
*
* @param n
* @return
*/
public String getRegName(int n) {
return getCore().getRegName(n);
}
} |
package edu.cshl.schatz.jnomics.tools;
import edu.cshl.schatz.jnomics.cli.JnomicsArgument;
import edu.cshl.schatz.jnomics.io.ThreadedStreamConnector;
import edu.cshl.schatz.jnomics.mapreduce.JnomicsCounter;
import edu.cshl.schatz.jnomics.mapreduce.JnomicsMapper;
import edu.cshl.schatz.jnomics.ob.ReadCollectionWritable;
import edu.cshl.schatz.jnomics.ob.ReadWritable;
import edu.cshl.schatz.jnomics.ob.SAMRecordWritable;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Counter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class BWAMap extends JnomicsMapper<ReadCollectionWritable,NullWritable,SAMRecordWritable,NullWritable> {
private File[] tmpFiles;
private String[] aln_cmds_pair,aln_cmds_single;
private String sampe_cmd, samse_cmd;
private Process process;
private Throwable readerError = null;
private final JnomicsArgument bwa_aln_opts_arg = new JnomicsArgument("bwa_aln_opts",
"Alignment options for BWA Align", false);
private final JnomicsArgument bwa_sampe_opts_arg = new JnomicsArgument("bwa_sampe_opts",
"Alignment options for BWA Sampe", false);
private final JnomicsArgument bwa_samse_opts_arg = new JnomicsArgument("bwa_samse_opts",
"Alignment options for BWA Samse", false);
private final JnomicsArgument bwa_idx_arg = new JnomicsArgument("bwa_index", "bwa index location", true);
private final JnomicsArgument bwa_binary_arg = new JnomicsArgument("bwa_binary", "bwa binary location", true);
@Override
protected void setup(final Context context) throws IOException,InterruptedException {
String bwa_aln_opts = context.getConfiguration().get(bwa_aln_opts_arg.getName(),"");
String bwa_sampe_opts = context.getConfiguration().get(bwa_sampe_opts_arg.getName(), "");
String bwa_samse_opts = context.getConfiguration().get(bwa_samse_opts_arg.getName(),"");
String bwa_idx = context.getConfiguration().get(bwa_idx_arg.getName());
String bwa_binary = context.getConfiguration().get(bwa_binary_arg.getName());
if(!new File(bwa_binary).exists())
throw new IOException("Can't find bwa binary: " + bwa_binary);
String taskAttemptId = context.getTaskAttemptID().toString();
tmpFiles = new File[]{
new File(taskAttemptId + ".1.sai"),
new File(taskAttemptId + ".2.sai"),
new File(taskAttemptId + ".1.fq"),
new File(taskAttemptId + ".2.fq")
};
for(File file: tmpFiles){
file.createNewFile();
file.deleteOnExit();
}
System.out.println("BWA index--->"+bwa_idx);
aln_cmds_pair = new String[]{
String.format(
"%s aln %s %s %s",
bwa_binary, bwa_aln_opts, bwa_idx, tmpFiles[2]),
String.format(
"%s aln %s %s %s",
bwa_binary, bwa_aln_opts, bwa_idx, tmpFiles[3])
};
aln_cmds_single = new String[]{aln_cmds_pair[0]};
sampe_cmd = String.format(
"%s sampe %s %s %s %s %s %s",
bwa_binary, bwa_sampe_opts, bwa_idx, tmpFiles[0], tmpFiles[1],
tmpFiles[2], tmpFiles[3]
);
samse_cmd = String.format(
"%s samse %s %s %s %s",
bwa_binary, bwa_samse_opts, bwa_idx, tmpFiles[0], tmpFiles[2]
);
}
@Override
public void run(final Context context) throws IOException, InterruptedException {
setup(context);
/** Write Temp Files **/
BufferedOutputStream tmpWriter1 = new BufferedOutputStream(new FileOutputStream(tmpFiles[2]));
BufferedOutputStream tmpWriter2 = new BufferedOutputStream(new FileOutputStream(tmpFiles[3]));
System.out.println("Tmp Files
System.out.println(tmpFiles[2]);
System.out.println(tmpFiles[3]);
System.out.println("
List<ReadWritable> reads;
boolean first=true, paired=false;
while(context.nextKeyValue()){
reads = context.getCurrentKey().getReads();
tmpWriter1.write(reads.get(0).getFastqString().getBytes());
tmpWriter1.write("\n".getBytes());
if(reads.size() == 2){
if(first)
paired=true;
tmpWriter2.write(reads.get(1).getFastqString().getBytes());
tmpWriter2.write("\n".getBytes());
}
}
tmpWriter1.close();
tmpWriter2.close();
Thread connecterr,connectout;
System.out.println("launching alignment");
/**Launch Processes **/
int idx = 0;
FileOutputStream fout;
for(String cmd: paired ? aln_cmds_pair : aln_cmds_single){
process = Runtime.getRuntime().exec(cmd);
System.out.println(cmd);
// Reattach stderr and write System.stdout to tmp file
connecterr = new Thread(
new ThreadedStreamConnector(process.getErrorStream(), System.err){
@Override
public void progress() {
context.progress();
}
});
fout = new FileOutputStream(tmpFiles[idx]);
connectout = new Thread(new ThreadedStreamConnector(process.getInputStream(),fout));
connecterr.start();connectout.start();
connecterr.join();connectout.join();
process.waitFor();
fout.close();
idx++;
context.progress();
}
System.out.println("running sampe/samse");
/**Launch sampe command*/
final Process sam_process = Runtime.getRuntime().exec(paired ? sampe_cmd : samse_cmd);
connecterr = new Thread(new ThreadedStreamConnector(sam_process.getErrorStream(), System.err));
connecterr.start();
/** setup reader thread - reads lines from bwa stdout and print them to context **/
Thread readerThread = new Thread( new Runnable() {
private final SAMRecordWritable writableRecord = new SAMRecordWritable();
@Override
public void run() {
SAMFileReader reader = new SAMFileReader(sam_process.getInputStream());
reader.setValidationStringency(SAMFileReader.ValidationStringency.LENIENT);
Counter mapped_counter = context.getCounter(JnomicsCounter.Alignment.MAPPED);
Counter totalreads_counter = context.getCounter(JnomicsCounter.Alignment.TOTAL);
for(SAMRecord record: reader){
writableRecord.set(record);
totalreads_counter.increment(1);
if(writableRecord.getMappingQuality().get() != 0)
mapped_counter.increment(1);
try {
context.write(writableRecord,NullWritable.get());
context.progress();
}catch(Exception e){
readerError = e;
}
}
reader.close();
}
});
readerThread.start();
readerThread.join();
sam_process.waitFor();
connecterr.join();
System.out.println("deleteing tmp files");
for(File file: tmpFiles)
file.delete();
if(readerError != null){
System.err.println("Error Reading BWA sampe/samse Output with SAM Record Reader");
throw new IOException(readerError);
}
}
@Override
public Class getOutputKeyClass() {
return SAMRecordWritable.class;
}
@Override
public Class getOutputValueClass() {
return NullWritable.class;
}
@Override
public JnomicsArgument[] getArgs() {
return new JnomicsArgument[]{bwa_aln_opts_arg,bwa_binary_arg,bwa_idx_arg,bwa_sampe_opts_arg,bwa_samse_opts_arg};
}
} |
package com.intellij.execution;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.openapi.util.text.StringUtil.*;
public class CommandLineUtil {
private static final char INESCAPABLE_QUOTE = '\uEFEF'; // a random char, which is unlikely to encounter in an argument
private static final Pattern WIN_BACKSLASHES_PRECEDING_QUOTE = Pattern.compile("(\\\\+)(?=\"|$)");
private static final Pattern WIN_CARET_SPECIAL = Pattern.compile("[&<>()@^|!%]");
private static final Pattern WIN_QUOTE_SPECIAL = Pattern.compile("[ \t\"*?\\[{}~()\']"); // + glob [*?] + Cygwin glob [*?\[{}~] + [()']
private static final Pattern WIN_QUIET_COMMAND = Pattern.compile("((?:@\\s*)++)(.*)", Pattern.CASE_INSENSITIVE);
private static final char Q = '\"';
private static final String QQ = "\"\"";
@NotNull
public static String specialQuote(@NotNull String parameter) {
return quote(parameter, INESCAPABLE_QUOTE);
}
@NotNull
public static List<String> toCommandLine(@NotNull List<String> command) {
assert !command.isEmpty();
return toCommandLine(command.get(0), command.subList(1, command.size()));
}
@NotNull
public static List<String> toCommandLine(@NotNull String command, @NotNull List<String> parameters) {
return toCommandLine(command, parameters, Platform.current());
}
// please keep an implementation in sync with [junit-rt] ProcessBuilder.createProcess()
@NotNull
public static List<String> toCommandLine(@NotNull String command, @NotNull List<String> parameters, @NotNull Platform platform) {
List<String> commandLine = ContainerUtil.newArrayListWithCapacity(parameters.size() + 1);
commandLine.add(FileUtilRt.toSystemDependentName(command, platform.fileSeparator));
if (platform != Platform.WINDOWS) {
for (String parameter : parameters) {
if (isQuoted(parameter, INESCAPABLE_QUOTE)) {
// TODO do we need that on non-Windows? M.b. just remove these quotes? -- Eldar
parameter = quote(unquoteString(parameter, INESCAPABLE_QUOTE), Q);
}
commandLine.add(parameter);
}
}
else {
addToWindowsCommandLine(command, parameters, commandLine);
}
return commandLine;
}
private static void addToWindowsCommandLine(String command, List<String> parameters, List<? super String> commandLine) {
boolean isCmdParam = isWinShell(command);
int cmdInvocationDepth = isWinShellScript(command) ? 2 : isCmdParam ? 1 : 0;
QuoteFlag quoteFlag = new QuoteFlag(false);
for (int i = 0; i < parameters.size(); i++) {
String parameter = parameters.get(i);
parameter = unquoteString(parameter, INESCAPABLE_QUOTE);
boolean inescapableQuoting = !parameter.equals(parameters.get(i));
if (parameter.isEmpty()) {
commandLine.add(QQ);
continue;
}
if (isCmdParam && parameter.startsWith("/") && parameter.length() == 2) {
commandLine.add(parameter);
continue;
}
String parameterPrefix = "";
if (isCmdParam) {
Matcher m = WIN_QUIET_COMMAND.matcher(parameter);
if (m.matches()) {
parameterPrefix = m.group(1);
parameter = m.group(2);
}
if (parameter.equalsIgnoreCase("echo")) {
// no further quoting, only ^-escape and wrap the whole "echo ..." into double quotes
String parametersJoin = join(ContainerUtil.subList(parameters, i), " ");
quoteFlag.toggle();
parameter = escapeParameter(parametersJoin, quoteFlag, cmdInvocationDepth, false);
commandLine.add(parameter); // prefix is already included
break;
}
if (!parameter.equalsIgnoreCase("call")) {
isCmdParam = isWinShell(parameter);
if (isCmdParam || isWinShellScript(parameter)) {
cmdInvocationDepth++;
}
}
}
if (cmdInvocationDepth > 0 && !isCmdParam || inescapableQuoting) {
parameter = escapeParameter(parameter, quoteFlag, cmdInvocationDepth, !inescapableQuoting);
}
else {
parameter = backslashEscapeQuotes(parameter);
}
commandLine.add(parameterPrefix.isEmpty() ? parameter : parameterPrefix + parameter);
}
}
private static String escapeParameter(String s, QuoteFlag quoteFlag, int cmdInvocationDepth, boolean escapeQuotingInside) {
String escapingCarets = repeatSymbol('^', (1 << cmdInvocationDepth) - 1);
return escapeQuotingInside ? quoteEscape(s, quoteFlag, escapingCarets) : caretEscape(s, quoteFlag, escapingCarets);
}
/**
* Escape a parameter for passing it to CMD.EXE, that is only ^-escape and wrap it with double quotes,
* but do not touch any double quotes or backslashes inside.
*
* @param escapingCarets 2^n-1 carets for escaping the special chars
*/
private static String caretEscape(String s, QuoteFlag quoteFlag, String escapingCarets) {
StringBuilder sb = new StringBuilder().append(Q);
quoteFlag.toggle();
int lastPos = 0;
Matcher m = WIN_CARET_SPECIAL.matcher(s);
while (m.find()) {
quoteFlag.update(s, lastPos, m.start());
sb.append(s, lastPos, m.start());
if (!quoteFlag.enabled) sb.append(escapingCarets);
sb.append(m.group());
lastPos = m.end();
}
quoteFlag.update(s, lastPos, s.length());
sb.append(s, lastPos, s.length());
quoteFlag.toggle();
return sb.append(Q).toString();
}
/**
* Escape a parameter for passing it to Windows application through CMD.EXE, that is ^-escape + quote.
*
* @param escapingCarets 2^n-1 carets for escaping the special chars
*/
private static String quoteEscape(String s, QuoteFlag quoteFlag, String escapingCarets) {
StringBuilder sb = new StringBuilder();
int lastPos = 0;
Matcher m = WIN_CARET_SPECIAL.matcher(s);
while (m.find()) {
quoteFlag.update(s, lastPos, m.start());
appendQuoted(sb, s.substring(lastPos, m.start()));
String specialText = m.group();
boolean isCaret = specialText.equals("^");
if (isCaret) specialText = escapingCarets + specialText; // only a caret is escaped using carets
if (isCaret == quoteFlag.enabled) {
// a caret must be always outside quotes: close a quote temporarily, put a caret, reopen a quote
// rest special chars are always inside: quote and append them as usual
appendQuoted(sb, specialText); // works for both cases
}
else {
sb.append(specialText);
}
lastPos = m.end();
}
quoteFlag.update(s, lastPos, s.length());
appendQuoted(sb, s.substring(lastPos));
// JDK ProcessBuilder implementation on Windows checks each argument to contain whitespaces and encloses it in
// double quotes unless it's already quoted. Since our escaping logic is more complicated, we may end up with
// something like [^^"foo bar"], which is not a quoted string, strictly speaking; it would require additional
// quotes from the JDK's point of view, which in turn ruins the quoting and caret state inside the string.
// Here, we prepend and/or append a [""] token (2 quotes to preserve the parity), if necessary, to make the result
// look like a properly quoted string:
// [^^"foo bar"] -> [""^^"foo bar"] # starts and ends with quotes
if (!isQuoted(sb, Q) && indexOfAny(sb, " \t") >= 0) {
if (sb.charAt(0) != Q) sb.insert(0, QQ);
if (sb.charAt(sb.length() - 1) != Q) sb.append(QQ);
}
return sb.toString();
}
/*
* Appends the string to the buffer, quoting the former if necessary.
*/
private static void appendQuoted(StringBuilder sb, String s) {
if (s.isEmpty()) return;
s = backslashEscapeQuotes(s);
if (WIN_CARET_SPECIAL.matcher(s).find()) s = quote(s, Q);
// Can't just concatenate two quoted strings, like ["foo"] and ["bar"],
// the two quotes inside would be treated as ["] upon unescaping, that is: |
package com.intellij.ui;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.ui.EditableModel;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
public class CollectionListModel<T> extends AbstractListModel<T> implements EditableModel {
private final List<T> myItems;
public CollectionListModel(@NotNull final Collection<? extends T> items) {
myItems = new ArrayList<>(items);
}
@SuppressWarnings("UnusedParameters")
public CollectionListModel(@NotNull List<T> items, boolean useListAsIs) {
myItems = items;
}
public CollectionListModel(@NotNull List<? extends T> items) {
myItems = ContainerUtilRt.newArrayList(items);
}
@SafeVarargs
public CollectionListModel(@NotNull T... items) {
myItems = Arrays.asList(items);
}
@NotNull
protected final List<T> getInternalList() {
return myItems;
}
@Override
public int getSize() {
return myItems.size();
}
@Override
public T getElementAt(final int index) {
return myItems.get(index);
}
public void add(final T element) {
int i = myItems.size();
myItems.add(element);
fireIntervalAdded(this, i, i);
}
public void add(int i,final T element) {
myItems.add(i, element);
fireIntervalAdded(this, i, i);
}
public void add(@NotNull final List<? extends T> elements) {
addAll(myItems.size(), elements);
}
public void addAll(int index, @NotNull final List<? extends T> elements) {
if (elements.isEmpty()) return;
myItems.addAll(index, elements);
fireIntervalAdded(this, index, index + elements.size() - 1);
}
public void remove(@NotNull T element) {
int index = getElementIndex(element);
if (index != -1) {
remove(index);
}
}
public void setElementAt(@NotNull final T item, final int index) {
itemReplaced(myItems.set(index, item), item);
fireContentsChanged(this, index, index);
}
@SuppressWarnings("UnusedParameters")
protected void itemReplaced(@NotNull T existingItem, @Nullable T newItem) {
}
public void remove(final int index) {
T item = myItems.remove(index);
if (item != null) {
itemReplaced(item, null);
}
fireIntervalRemoved(this, index, index);
}
public void removeAll() {
int size = myItems.size();
if (size > 0) {
myItems.clear();
fireIntervalRemoved(this, 0, size - 1);
}
}
public void contentsChanged(@NotNull final T element) {
int i = myItems.indexOf(element);
fireContentsChanged(this, i, i);
}
public void allContentsChanged() {
fireContentsChanged(this, 0, myItems.size() - 1);
}
public void sort(final Comparator<? super T> comparator) {
Collections.sort(myItems, comparator);
}
@NotNull
public List<T> getItems() {
return Collections.unmodifiableList(myItems);
}
public void replaceAll(@NotNull final List<? extends T> elements) {
removeAll();
add(elements);
}
@Override
public void addRow() {
}
@Override
public void removeRow(int index) {
remove(index);
}
@Override
public void exchangeRows(int oldIndex, int newIndex) {
Collections.swap(myItems, oldIndex, newIndex);
fireContentsChanged(this, oldIndex, oldIndex);
fireContentsChanged(this, newIndex, newIndex);
}
@Override
public boolean canExchangeRows(int oldIndex, int newIndex) {
return true;
}
@NonNls
@Override
public String toString() {
return getClass().getName() + " (" + getSize() + " elements)";
}
public List<T> toList() {
return new ArrayList<>(myItems);
}
public int getElementIndex(T item) {
return myItems.indexOf(item);
}
public boolean isEmpty() {
return myItems.isEmpty();
}
public boolean contains(T item) {
return getElementIndex(item) >= 0;
}
public void removeRange(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException("fromIndex must be <= toIndex");
}
for(int i = toIndex; i >= fromIndex; i
itemReplaced(myItems.remove(i), null);
}
fireIntervalRemoved(this, fromIndex, toIndex);
}
} |
package org.jruby.ext.thread_safe;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMap;
import org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMapV8;
import org.jruby.ext.thread_safe.jsr166e.nounsafe.*;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.Library;
import java.io.IOException;
import java.util.Map;
import static org.jruby.runtime.Visibility.PRIVATE;
/**
* Native Java implementation to avoid the JI overhead.
*
* @author thedarkone
*/
public class JRubyCacheBackendLibrary implements Library {
public void load(Ruby runtime, boolean wrap) throws IOException {
RubyClass jrubyRefClass = runtime.defineClassUnder("JRubyCacheBackend", runtime.getObject(), BACKEND_ALLOCATOR, runtime.getModule("ThreadSafe"));
jrubyRefClass.setAllocator(BACKEND_ALLOCATOR);
jrubyRefClass.defineAnnotatedMethods(JRubyCacheBackend.class);
}
private static final ObjectAllocator BACKEND_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new JRubyCacheBackend(runtime, klazz);
}
};
@JRubyClass(name="JRubyCacheBackend", parent="Object")
public static class JRubyCacheBackend extends RubyObject {
// Defaults used by the CHM
static final int DEFAULT_INITIAL_CAPACITY = 16;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public static final boolean CAN_USE_UNSAFE_CHM = canUseUnsafeCHM();
private ConcurrentHashMap<IRubyObject, IRubyObject> map;
private static ConcurrentHashMap<IRubyObject, IRubyObject> newCHM(int initialCapacity, float loadFactor) {
if (CAN_USE_UNSAFE_CHM) {
return new ConcurrentHashMapV8<IRubyObject, IRubyObject>(initialCapacity, loadFactor);
} else {
return new org.jruby.ext.thread_safe.jsr166e.nounsafe.ConcurrentHashMapV8<IRubyObject, IRubyObject>(initialCapacity, loadFactor);
}
}
private static ConcurrentHashMap<IRubyObject, IRubyObject> newCHM() {
return newCHM(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
private static boolean canUseUnsafeCHM() {
try {
new org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMapV8(); // force class load and initialization
return true;
} catch (Throwable t) { // ensuring we really do catch everything
// Doug's Unsafe setup errors always have this "Could not ini.." message
if (isCausedBySecurityException(t)) {
return false;
}
throw (t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t));
}
}
private static boolean isCausedBySecurityException(Throwable t) {
while (t != null) {
if ((t.getMessage() != null && t.getMessage().contains("Could not initialize intrinsics")) || t instanceof SecurityException) {
return true;
}
t = t.getCause();
}
return false;
}
public JRubyCacheBackend(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context) {
map = newCHM();
return context.getRuntime().getNil();
}
@JRubyMethod
public IRubyObject initialize(ThreadContext context, IRubyObject options) {
map = toCHM(context, options);
return context.getRuntime().getNil();
}
private ConcurrentHashMap<IRubyObject, IRubyObject> toCHM(ThreadContext context, IRubyObject options) {
Ruby runtime = context.getRuntime();
if (!options.isNil() && options.respondsTo("[]")) {
IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity"));
IRubyObject rLoadFactor = options.callMethod(context, "[]", runtime.newSymbol("load_factor"));
int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY;
float loadFactor = !rLoadFactor.isNil() ? (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR;
return newCHM(initialCapacity, loadFactor);
} else {
return newCHM();
}
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(ThreadContext context, IRubyObject key) {
IRubyObject value;
return ((value = map.get(key)) == null) ? context.getRuntime().getNil() : value;
}
@JRubyMethod(name = {"[]="}, required = 2)
public IRubyObject op_aset(IRubyObject key, IRubyObject value) {
map.put(key, value);
return value;
}
@JRubyMethod
public IRubyObject put_if_absent(IRubyObject key, IRubyObject value) {
IRubyObject result = map.putIfAbsent(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject compute_if_absent(final ThreadContext context, final IRubyObject key, final Block block) {
return map.computeIfAbsent(key, new ConcurrentHashMap.Fun<IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key) {
return block.yieldSpecific(context);
}
});
}
@JRubyMethod
public IRubyObject compute_if_present(final ThreadContext context, final IRubyObject key, final Block block) {
IRubyObject result = map.computeIfPresent(key, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key, IRubyObject oldValue) {
IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject compute(final ThreadContext context, final IRubyObject key, final Block block) {
IRubyObject result = map.compute(key, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject key, IRubyObject oldValue) {
IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject merge_pair(final ThreadContext context, final IRubyObject key, final IRubyObject value, final Block block) {
IRubyObject result = map.merge(key, value, new ConcurrentHashMap.BiFun<IRubyObject, IRubyObject, IRubyObject>() {
@Override
public IRubyObject apply(IRubyObject oldValue, IRubyObject newValue) {
IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue);
return result.isNil() ? null : result;
}
});
return result == null ? context.getRuntime().getNil() : result;
}
@JRubyMethod
public RubyBoolean replace_pair(IRubyObject key, IRubyObject oldValue, IRubyObject newValue) {
return getRuntime().newBoolean(map.replace(key, oldValue, newValue));
}
@JRubyMethod(name = "key?", required = 1)
public RubyBoolean has_key_p(IRubyObject key) {
return map.containsKey(key) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod
public IRubyObject key(IRubyObject value) {
final IRubyObject key = map.findKey(value);
return key == null ? getRuntime().getNil() : key;
}
@JRubyMethod
public IRubyObject replace_if_exists(IRubyObject key, IRubyObject value) {
IRubyObject result = map.replace(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject get_and_set(IRubyObject key, IRubyObject value) {
IRubyObject result = map.put(key, value);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public IRubyObject delete(IRubyObject key) {
IRubyObject result = map.remove(key);
return result == null ? getRuntime().getNil() : result;
}
@JRubyMethod
public RubyBoolean delete_pair(IRubyObject key, IRubyObject value) {
return getRuntime().newBoolean(map.remove(key, value));
}
@JRubyMethod
public IRubyObject clear() {
map.clear();
return this;
}
@JRubyMethod
public IRubyObject each_pair(ThreadContext context, Block block) {
for (Map.Entry<IRubyObject,IRubyObject> entry : map.entrySet()) {
block.yieldSpecific(context, entry.getKey(), entry.getValue());
}
return this;
}
@JRubyMethod
public RubyFixnum size(ThreadContext context) {
return context.getRuntime().newFixnum(map.size());
}
@JRubyMethod
public IRubyObject get_or_default(IRubyObject key, IRubyObject defaultValue) {
return map.getValueOrDefault(key, defaultValue);
}
@JRubyMethod(visibility = PRIVATE)
public JRubyCacheBackend initialize_copy(ThreadContext context, IRubyObject other) {
map = newCHM();
return this;
}
}
} |
package ch.ffhs.esa.bewegungsmelder;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.FragmentManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import ch.ffhs.esa.bewegungsmelder.KontaktDBContract.KontaktTabelle;
public class AddContact extends Activity implements
OnItemClickListener {
private static final int ADD_KONTAKT_DIALOG = 1;
private static final String TAG = AddContact.class.getSimpleName();
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
// Show the Up button in the action bar.
setupActionBar();
updateList();
listView = (ListView) findViewById(R.id.updateList);
listView.setOnItemClickListener(this);
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_contact, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void contactAdd (View view){
/*
Intent intent = new Intent(this, KontaktManuellHinzu.class);
startActivity(intent);
*/
FragmentManager manager = getFragmentManager();
KontaktDialogFragment d = new KontaktDialogFragment ();
d.show(manager, "KontaktDialogFragment");
}
public void updateList(){
Log.d(TAG, "Updating List");
List<Kontakt> updatelist = new ArrayList<Kontakt>();
//ArrayList<String> updatelist = new ArrayList<String>();
KontaktDBHelper mDbHelper = new KontaktDBHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
KontaktTabelle._ID,
KontaktTabelle.COLUMN_NAME_NAME,
KontaktTabelle.COLUMN_NAME_NUMBER,
};
Cursor c = null;
try {
c = db.query(KontaktTabelle.TABLE_NAME, projection, null, null, null, null, null);
} catch (Exception e) {
c = db.rawQuery("SELECT * FROM " + KontaktTabelle.TABLE_NAME, null);
for (int i = 0; i < c.getColumnCount();i++){
Log.d(TAG, "Catched an exception on query!!!! Raw Query of column " +i + ":" + c.getColumnName(i) );
}
e.printStackTrace();
}
Log.d(TAG, "Cursor: " + c.toString());
if (c.moveToFirst()){
do {
String name = c.getString(1);
String phoneNumber = c.getString(2);
Kontakt objContact = new Kontakt();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
updatelist.add(objContact);
} while (c.moveToNext());
}
KontaktAdapter objAdapter = new KontaktAdapter(this, R.layout.alluser_row, updatelist);
setContentView(R.layout.activity_add_contact);
ListView list = (ListView) findViewById(R.id.updateList);
list.setAdapter(objAdapter);
}
@Override
public void onItemClick(AdapterView<?> listView, View v, int position, long id) {
Toast.makeText(this, "Ich wurde geklickt" , Toast.LENGTH_SHORT).show();
}
}; |
package ch.ntb.inf.deep.loader;
import ch.ntb.inf.deep.config.Configuration;
import ch.ntb.inf.deep.config.Parser;
import ch.ntb.inf.deep.config.Register;
import ch.ntb.inf.deep.linkerPPC.Linker;
import ch.ntb.inf.deep.linkerPPC.TargetMemorySegment;
import ch.ntb.inf.deep.strings.HString;
import ch.ntb.inf.libusbJava.USBException;
import ch.ntb.mcdp.bdi.BDIException;
import ch.ntb.mcdp.targets.mpc555.BDI;
import ch.ntb.mcdp.usb.Device;
import ch.ntb.mcdp.usb.DeviceFactory;
/**
* Creates an USB connection to the target.<br>
* The USB and MCDP projects have to be in the class path!!
*/
public class UsbMpc555Loader extends Downloader {
private static UsbMpc555Loader loader;
/**
* Target
*/
private BDI mpc;
/**
* USB Device
*/
private Device dev;
private UsbMpc555Loader(){
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#init()
*/
@Override
public synchronized void init() throws DownloaderException {
baseAddress = Configuration.getValueFor(HString.getHString("IMB"));
//check if connection is open
if(!this.isConnected()){
this.openConnection();
}
this.resetTarget();
// initialize Memory
initRegisters();
// clear the GPRs
clearGPRs();
long b = Long.valueOf(0x4004000000000000l);
setFPR(0, b);
setFPR(1, b);
setFPR(2, b);
setFPR(3, b);
setFPR(4, b);
setFPR(5, b);
setFPR(6, b);
setFPR(7, b);
setFPR(8, b);
// /**
// * Parse a Ramimage and write the code into the memory
// *
// * @param path
// * @throws FileNotFoundException
// */
// protected synchronized void parseAndWriteCode(String path) {
// String s;
// int count =0;
// int memAddr=0;
// try {
// FileReader fr = new FileReader(path);
// BufferedReader br = new BufferedReader(fr);
// while ((s = br.readLine()) != null) {
// if(s.charAt(0)!='\t'){
// s = s.substring(1);
// memAddr= Integer.decode(s);
// }else{
// s=s.substring(2);
// setMem(memAddr, Integer.decode(s), 4);
// count++;
// memAddr=memAddr+4;
// System.out.println(count);
// } catch (IOException e) {
// e.printStackTrace();
// // while (dis.available() > 0) {
// // code.add(dis.readInt());
// catch (NumberFormatException e) {
// System.err.println("Count "+ count);
// e.printStackTrace();
// } catch (DownloaderException e) {
// e.printStackTrace();
/**
* Set program counter to the base address
*
* @throws DownloaderException
*/
protected synchronized void resetProgramCtr(int address)
throws DownloaderException {
try {
// set SRR0 to start of instructions
mpc.writeSPR(26, address);
checkValue(mpc.readSPR(26), address);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#writeCode()
*/
@Override
protected synchronized void writeCode() throws DownloaderException {
// get code from the Linker
if (!isFreezeAsserted()) {
System.out.println("Bdi is not in Debug mode!");
}
TargetMemorySegment image = Linker.targetImage;
while (image != null) {
// TODO remove Hack, solve it proper!!!!!
int dataSizeToTransfer = image.data.length;
int startAddr = image.startAddress;
int index = 0;
while (dataSizeToTransfer > 0) {
//limitation for fast downlod is 101 Words
int[] data = new int[100];
if(dataSizeToTransfer < 101){
data = new int[dataSizeToTransfer];
}
for(int i = 0; i < data.length; i++){
data[i]= image.data[index++];
}
try {
mpc.startFastDownload(startAddr);
mpc.fastDownload(data, data.length);
mpc.stopFastDownload();
} catch (BDIException e) {
e.printStackTrace();
}
dataSizeToTransfer -= data.length;
startAddr += data.length * 4;
}
image = image.next;
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#initRegisters()
*/
@Override
protected synchronized void initRegisters() throws DownloaderException {
try {
Register root = Configuration.getInitializedRegisters();
Register current = root;
while (current != null) {
switch (current.getType()) {
case Parser.sSPR:
mpc.writeSPR(current.getAddress(), current.getInit()
.getValue());
break;
case Parser.sIOR:
mpc.writeMem(current.getAddress(), current.getInit()
.getValue(), current.getSize());
break;
case Parser.sMSR:
mpc.writeMSR(current.getInit().getValue());
break;
case Parser.sCR:
mpc.writeCR(current.getInit().getValue());
break;
case Parser.sFPSCR:
mpc.writeFPSCR(current.getInit().getValue());
break;
default:
break;
}
current = current.nextWithInitValue;
}
// Check if all is set fine
current = root;
while (current != null) {
switch (current.getType()) {
case Parser.sSPR:
checkValue(mpc.readSPR(current.getAddress()), current
.getInit().getValue());
break;
case Parser.sIOR:
checkValue(mpc.readMem(current.getAddress(), current
.getSize()), current.getInit().getValue());
break;
case Parser.sMSR:
checkValue(mpc.readMSR(), current.getInit().getValue());
break;
case Parser.sCR:
checkValue(mpc.readCR(), current.getInit().getValue());
break;
case Parser.sFPSCR:
checkValue(mpc.readFPSCR(), current.getInit().getValue());
break;
default:
break;
}
current = current.nextWithInitValue;
}
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#resetTarget()
*/
@Override
public synchronized void resetTarget() throws DownloaderException {
try {
// make a hard reset
mpc.reset_target();
/*
* Do not check the freeze signal on the target because it is set
* only after the following memory writes
*/
boolean cf = mpc.isCheckFreezeOnTarget();
mpc.setCheckFreezeOnTarget(false);
// assign pin to Freeze output
mpc.writeMem(0x02FC000, 0x40000, 4);
// enable bus monitor,disable watchdog timer
mpc.writeMem(0x02FC004, 0x0FFFFFF83, 4);
// SCCR, switch off EECLK for download
mpc.writeMem(0x02FC280, 0x08121C100, 4);
mpc.setCheckFreezeOnTarget(cf);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#startTarget()
*/
@Override
public synchronized void startTarget() throws DownloaderException {
try {
mpc.go();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#stopTarget()
*/
@Override
public synchronized void stopTarget() throws DownloaderException {
try {
mpc.break_();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#internalBreakpoint()
*/
@Override
public synchronized void internalBreakpoint() throws DownloaderException {
try {
mpc.prologue();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#readGPRs()
*/
@Override
public synchronized int[] readGPRs() throws DownloaderException {
//RegisterMap regMap = Configuration.getRegisterMap();
//int[] gprs = new int[regMap.getNofGprs()]; TODO this it the orignal line
int[] gprs = new int[32];
for (int j = 0; j < gprs.length; j++) {
gprs[j] = getGPR(j);
}
return gprs;
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#setGPRs(java.util.Map)
*/
@Override
public synchronized void setGPRs(int[][] gprs) throws DownloaderException {
for (int i = 0; i < gprs.length; i++) {
setGPR(gprs[i][0], gprs[i][1]);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#setGPR(int,
* int)
*/
@Override
public synchronized void setGPR(int no, int value)
throws DownloaderException {
try {
mpc.writeGPR(no, value);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#getGPR(int)
*/
@Override
public synchronized int getGPR(int no) throws DownloaderException {
int value = 0;
try {
value = mpc.readGPR(no);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
/**
* Sets all GPRs to 0
*
* @throws DownloaderException
*/
public synchronized void clearGPRs() throws DownloaderException {
//for (int i = 0; i < Configuration.getRegisterMap().getNofGprs(); i++) {TODO this it the orignal line
for (int i = 0; i < 32; i++){
setGPR(i, 0);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#getCR()
*/
@Override
public synchronized int getCR() throws DownloaderException {
int crReg = 0;
try {
crReg = mpc.readCR();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return crReg;
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#setCR(int)
*/
@Override
public synchronized void setCR(int value) throws DownloaderException {
try {
mpc.writeCR(value);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#isFreezeAsserted()
*/
@Override
public synchronized boolean isFreezeAsserted() throws DownloaderException {
boolean freeze = false;
try {
freeze = mpc.isFreezeAsserted();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return freeze;
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#setSPR(int,
* int)
*/
@Override
public synchronized void setSPR(int no, int value)
throws DownloaderException {
try {
mpc.writeSPR(no, value);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#getSPR(int)
*/
@Override
public synchronized int getSPR(int no) throws DownloaderException {
int value = 0;
try {
value = mpc.readSPR(no);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
public synchronized long getFPR(int no) throws DownloaderException {
long value = 0;
int temp;
try {
temp = mpc.readMem(baseAddress, 4);
value = mpc.readFPR(no, baseAddress);
mpc.writeMem(baseAddress, temp, 4);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
public synchronized void setFPR(int no, long value)
throws DownloaderException {
int temp;
try {
temp = mpc.readMem(baseAddress, 4);
mpc.writeFPR(no, baseAddress, value);
mpc.writeMem(baseAddress, temp, 4);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
public synchronized int getFPSCR() throws DownloaderException {
int value = 0;
try {
value = mpc.readFPSCR();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
public synchronized int getMSR() throws DownloaderException {
int value = 0;
try {
value = mpc.readMSR();
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#getMem(int,
* int)
*/
@Override
public synchronized int getMem(int addr, int size)
throws DownloaderException {
int value = 0;
try {
value = mpc.readMem(addr, size);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
return value;
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#setMem(int,
* int, int)
*/
@Override
public synchronized void setMem(int addr, int value, int size)
throws DownloaderException {
try {
mpc.writeMem(addr, value, size);
} catch (BDIException e) {
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* Check if the register is written correct
*
* @param i
* Value 1
* @param j
* Value 2
*/
private synchronized static void checkValue(int i, int j) {
if (i != j) {
if ((i == -1 && j == 0) || (i == 0 && j == -1))
return;
throw new RuntimeException("i (" + i + ") != j (" + j + ")");
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#openConnection()
*/
@Override
public synchronized void openConnection() throws DownloaderException {
dev = DeviceFactory.getDevice();
try {
mpc = new BDI(dev);
// System.out.println("USB dev.open()");
dev.open();
} catch (USBException e) {
try {
dev.close();
} catch (USBException e1) {
// nothing to do
}
throw new DownloaderException(e.getMessage(), e);
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#closeConnection()
*/
@Override
public synchronized void closeConnection() {
try {
dev.close();
} catch (USBException e) {
// do nothing
}
}
/**
* (non-Javadoc)
*
* @see ch.ntb.mpc555.register.controller.javaEnv.crosscompiler.download.Downloader#isConnected()
*/
@Override
public synchronized boolean isConnected() {
return dev.isOpen();
}
} |
package com.splicemachine.derby.impl.sql.compile;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.sql.compile.*;
import com.splicemachine.db.iapi.sql.dictionary.ConglomerateDescriptor;
public class MergeSortJoinStrategy extends BaseCostedHashableJoinStrategy {
public MergeSortJoinStrategy() {
}
@Override
public boolean feasible(Optimizable innerTable,
OptimizablePredicateList predList,
Optimizer optimizer,
CostEstimate outerCost,boolean wasHinted) throws StandardException {
// if (CostUtils.isThisBaseTable(optimizer))
// return false;
return super.feasible(innerTable, predList, optimizer,outerCost,wasHinted);
}
@Override
public String getName() {
return "SORTMERGE";
}
@Override
public String toString(){
return "MergeSortJoin";
}
/** @see JoinStrategy#multiplyBaseCostByOuterRows */
public boolean multiplyBaseCostByOuterRows() {
return true;
}
/**
* @see JoinStrategy#resultSetMethodName
*/
public String resultSetMethodName(boolean bulkFetch, boolean multiprobe) {
if (bulkFetch)
return "getBulkTableScanResultSet";
else if (multiprobe)
return "getMultiProbeTableScanResultSet";
else
return "getTableScanResultSet";
}
/**
* @see JoinStrategy#joinResultSetMethodName
*/
public String joinResultSetMethodName() {
return "getMergeSortJoinResultSet";
}
/**
* @see JoinStrategy#halfOuterJoinResultSetMethodName
*/
public String halfOuterJoinResultSetMethodName() {
return "getMergeSortLeftOuterJoinResultSet";
}
/**
*
* Right Side Cost + (LeftSideRows+RightSideRows)*WriteCost
*
*/
@Override
public void estimateCost(Optimizable innerTable,
OptimizablePredicateList predList,
ConglomerateDescriptor cd,
CostEstimate outerCost,
Optimizer optimizer,
CostEstimate innerCost) throws StandardException{
if(outerCost.isUninitialized() ||(outerCost.localCost()==0d && outerCost.getEstimatedRowCount()==1.0d)){
RowOrdering ro=outerCost.getRowOrdering();
if(ro!=null)
outerCost.setRowOrdering(ro); //force a cloning
return; //actually a scan, don't change the cost
}
//set the base costing so that we don't lose the underlying table costs
innerCost.setBase(innerCost.cloneMe());
/*
* MergeSortJoins are complex, and likely to change. We break this up
* into two different versions: a "TempTable" version, and a "Spark version".
* Currently, the "Spark version" is unimplemented, but when this merges
* in we'll need to re-cost that
*/
tempTableCost(innerTable,predList,cd,outerCost,optimizer,innerCost);
}
private void tempTableCost(Optimizable innerTable,
OptimizablePredicateList predList,
ConglomerateDescriptor cd,
CostEstimate outerCost,
Optimizer optimizer,
CostEstimate innerCost) throws StandardException{
double innerRowCount=innerCost.rowCount();
double outerRowCount=outerCost.rowCount();
if(innerRowCount==0d){
if(outerRowCount==0d) return; //we don't expect to change the cost any when we run this, because we expect to be empty
else{
/*
* For the purposes of estimation, we will assume that the innerRowCount = 1, so that
* we can safely compute the estimate. The difference between 1 and 0 is generally negliable,
* and it will allow us to get a sensical cost estimate
*/
innerRowCount = 1d;
}
}else if(outerRowCount==0d){
/*
* For the purposes of safe estimation, we assume that we are returning at least one row. The
* cost difference is relatively negligiable, but this way we avoid NaNs and so forth.
*/
outerRowCount = 1d;
}
double outerRemoteCost=outerCost.remoteCost();
double innerRemoteCost=innerCost.remoteCost();
double outerSortCost = (outerCost.localCost()+outerRemoteCost)/outerCost.partitionCount();
double innerSortCost = (innerCost.localCost()+innerRemoteCost)/innerCost.partitionCount();
double sortCost = Math.max(outerSortCost,innerSortCost);
double perRowLocalLatency = outerCost.localCost()/(2*outerRowCount);
perRowLocalLatency+=innerCost.localCost()/(2*innerRowCount);
double joinSelectivity = estimateJoinSelectivity(innerTable,cd,predList,innerRowCount);
double mergeRows = joinSelectivity*(outerRowCount*innerRowCount);
int mergePartitions = (int)Math.round(Math.min(16,mergeRows));
double mergeLocalCost = perRowLocalLatency*(outerRowCount+innerRowCount);
double avgOpenCost = (outerCost.getOpenCost()+innerCost.getOpenCost())/2;
double avgCloseCost = (outerCost.getCloseCost()+innerCost.getCloseCost())/2;
mergeLocalCost+=mergePartitions*(avgOpenCost+avgCloseCost);
double mergeRemoteCost = getTotalRemoteCost(outerRemoteCost,innerRemoteCost,outerRowCount,innerRowCount,mergeRows);
double mergeHeapSize = getTotalHeapSize(outerCost.getEstimatedHeapSize(),
innerCost.getEstimatedHeapSize(),
outerRowCount,
innerRowCount,
mergeRows);
double totalLocalCost = sortCost+mergeLocalCost;
innerCost.setRemoteCost(mergeRemoteCost);
innerCost.setLocalCost(totalLocalCost);
innerCost.setRowCount(mergeRows);
innerCost.setEstimatedHeapSize((long)mergeHeapSize);
innerCost.setNumPartitions(mergePartitions);
/*
* The TEMP algorithm re-sorts data according to join keys, which eliminates the sort order
* of the data.
*/
innerCost.setRowOrdering(null);
}
@Override
public JoinStrategyType getJoinStrategyType() {
return JoinStrategyType.MERGE_SORT;
}
// DB-3460: For an outer left join query, sort merge join was ruled out because it did not qualify memory
// requirement for hash joins. Sort merge join requires substantially less memory than other hash joins, so
// maxCapacity() is override to return a very large integer to bypass memory check.
@Override
public int maxCapacity(int userSpecifiedCapacity,int maxMemoryPerTable,double perRowUsage){
return Integer.MAX_VALUE;
}
} |
package org.rstudio.studio.client.workbench.views.source.editors.text;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.rstudio.core.client.*;
import org.rstudio.core.client.Invalidation.Token;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.EnsureVisibleHandler;
import org.rstudio.core.client.events.HasEnsureVisibleHandlers;
import org.rstudio.core.client.files.FileSystemContext;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.widget.*;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.ChangeFontSizeEvent;
import org.rstudio.studio.client.application.events.ChangeFontSizeHandler;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.*;
import org.rstudio.studio.client.common.filetypes.FileType;
import org.rstudio.studio.client.common.filetypes.FileTypeCommands;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.common.filetypes.SweaveFileType;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.synctex.Synctex;
import org.rstudio.studio.client.common.synctex.SynctexUtils;
import org.rstudio.studio.client.common.synctex.model.SourceLocation;
import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewEvent;
import org.rstudio.studio.client.htmlpreview.model.HTMLPreviewParams;
import org.rstudio.studio.client.pdfviewer.events.ShowPDFViewerEvent;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.ui.FontSizeManager;
import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeEvent;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeHandler;
import org.rstudio.studio.client.workbench.views.files.model.FileChange;
import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent;
import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay.AnchoredSelection;
import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeList.ContainsPredicate;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceFold;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu;
import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler;
import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent;
import org.rstudio.studio.client.workbench.views.source.events.SourceNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.*;
import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsDiffEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsHistoryEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRevertFileEvent;
import java.util.ArrayList;
import java.util.HashSet;
public class TextEditingTarget implements EditingTarget
{
interface MyCommandBinder
extends CommandBinder<Commands, TextEditingTarget>
{
}
private static final MyCommandBinder commandBinder =
GWT.create(MyCommandBinder.class);
public interface Display extends TextDisplay,
WarningBarDisplay,
HasEnsureVisibleHandlers
{
HasValue<Boolean> getSourceOnSave();
void ensureVisible();
void showFindReplace();
StatusBar getStatusBar();
boolean isAttached();
void debug_forceTopsToZero();
void debug_dumpContents();
void debug_importDump();
}
private class SaveProgressIndicator implements ProgressIndicator
{
public SaveProgressIndicator(FileSystemItem file,
TextFileType fileType,
Command executeOnSuccess)
{
file_ = file;
newFileType_ = fileType;
executeOnSuccess_ = executeOnSuccess;
}
public void onProgress(String message)
{
}
public void clearProgress()
{
}
public void onCompleted()
{
// don't need to check again soon because we just saved
// (without this and when file monitoring is active we'd
// end up immediately checking for external edits)
externalEditCheckInterval_.reset(250);
if (newFileType_ != null)
fileType_ = newFileType_;
if (file_ != null)
{
ignoreDeletes_ = false;
commands_.reopenSourceDocWithEncoding().setEnabled(true);
name_.setValue(file_.getName(), true);
// Make sure tooltip gets updated, even if name hasn't changed
name_.fireChangeEvent();
dirtyState_.markClean();
}
if (newFileType_ != null)
{
// Make sure the icon gets updated, even if name hasn't changed
name_.fireChangeEvent();
updateStatusBarLanguage();
view_.adaptToFileType(newFileType_);
events_.fireEvent(new FileTypeChangedEvent());
if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave())
{
view_.getSourceOnSave().setValue(false, true);
}
}
if (executeOnSuccess_ != null)
executeOnSuccess_.execute();
}
public void onError(String message)
{
// in case the error occured saving a document that wasn't
// in the foreground
view_.ensureVisible();
globalDisplay_.showErrorMessage(
"Error Saving File",
message);
}
private final FileSystemItem file_;
private final TextFileType newFileType_;
private final Command executeOnSuccess_;
}
@Inject
public TextEditingTarget(Commands commands,
SourceServerOperations server,
EventBus events,
GlobalDisplay globalDisplay,
FileDialogs fileDialogs,
FileTypeRegistry fileTypeRegistry,
FileTypeCommands fileTypeCommands,
ConsoleDispatcher consoleDispatcher,
WorkbenchContext workbenchContext,
Session session,
Synctex synctex,
FontSizeManager fontSizeManager,
DocDisplay docDisplay,
UIPrefs prefs)
{
commands_ = commands;
server_ = server;
events_ = events;
globalDisplay_ = globalDisplay;
fileDialogs_ = fileDialogs;
fileTypeRegistry_ = fileTypeRegistry;
fileTypeCommands_ = fileTypeCommands;
consoleDispatcher_ = consoleDispatcher;
workbenchContext_ = workbenchContext;
session_ = session;
synctex_ = synctex;
fontSizeManager_ = fontSizeManager;
docDisplay_ = docDisplay;
dirtyState_ = new DirtyState(docDisplay_, false);
prefs_ = prefs;
compilePdfHelper_ = new TextEditingTargetCompilePdfHelper(docDisplay_);
previewHtmlHelper_ = new TextEditingTargetPreviewHtmlHelper();
docDisplay_.setRnwChunkOptionsProvider(compilePdfHelper_);
scopeHelper_ = new TextEditingTargetScopeHelper(docDisplay_);
addRecordNavigationPositionHandler(releaseOnDismiss_,
docDisplay_,
events_,
this);
docDisplay_.addKeyDownHandler(new KeyDownHandler()
{
public void onKeyDown(KeyDownEvent event)
{
NativeEvent ne = event.getNativeEvent();
int mod = KeyboardShortcut.getModifierValue(ne);
if ((mod == KeyboardShortcut.META || (mod == KeyboardShortcut.CTRL && !BrowseCap.hasMetaKey()))
&& ne.getKeyCode() == 'F')
{
event.preventDefault();
event.stopPropagation();
commands_.findReplace().execute();
}
else if (mod == KeyboardShortcut.ALT
&& ne.getKeyCode() == 189) // hyphen
{
event.preventDefault();
event.stopPropagation();
docDisplay_.insertCode(" <- ", false);
}
else if (mod == KeyboardShortcut.CTRL
&& ne.getKeyCode() == KeyCodes.KEY_UP
&& fileType_ == FileTypeRegistry.R)
{
event.preventDefault();
event.stopPropagation();
jumpToPreviousFunction();
}
else if (mod == KeyboardShortcut.CTRL
&& ne.getKeyCode() == KeyCodes.KEY_DOWN
&& fileType_ == FileTypeRegistry.R)
{
event.preventDefault();
event.stopPropagation();
jumpToNextFunction();
}
}
});
docDisplay_.addCommandClickHandler(new CommandClickEvent.Handler()
{
@Override
public void onCommandClick(CommandClickEvent event)
{
if (fileType_.canCompilePDF() &&
commands_.synctexSearch().isEnabled())
{
// warn firefox users that this doesn't really work in Firefox
if (BrowseCap.isFirefox() && !BrowseCap.isMacintosh())
SynctexUtils.maybeShowFirefoxWarning("PDF preview");
doSynctexSearch(true);
}
else
{
docDisplay_.goToFunctionDefinition();
}
}
});
}
@Override
public void recordCurrentNavigationPosition()
{
docDisplay_.recordCurrentNavigationPosition();
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
docDisplay_.navigateToPosition(position, recordCurrent);
}
@Override
public void restorePosition(SourcePosition position)
{
docDisplay_.restorePosition(position);
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
return docDisplay_.isAtSourceRow(position);
}
@Override
public void setCursorPosition(Position position)
{
docDisplay_.setCursorPosition(position);
}
private void jumpToPreviousFunction()
{
Scope jumpTo = scopeHelper_.getPreviousFunction(
docDisplay_.getCursorPosition());
if (jumpTo != null)
docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true);
}
private void jumpToNextFunction()
{
Scope jumpTo = scopeHelper_.getNextFunction(
docDisplay_.getCursorPosition());
if (jumpTo != null)
docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true);
}
public void initialize(SourceDocument document,
FileSystemContext fileContext,
FileType type,
Provider<String> defaultNameProvider)
{
id_ = document.getId();
fileContext_ = fileContext;
fileType_ = (TextFileType) type;
view_ = new TextEditingTargetWidget(commands_,
prefs_,
fileTypeRegistry_,
docDisplay_,
fileType_,
events_);
docUpdateSentinel_ = new DocUpdateSentinel(
server_,
docDisplay_,
document,
globalDisplay_.getProgressIndicator("Save File"),
dirtyState_,
events_);
name_.setValue(getNameFromDocument(document, defaultNameProvider), true);
docDisplay_.setCode(document.getContents(), false);
final ArrayList<Fold> folds = Fold.decode(document.getFoldSpec());
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
for (Fold fold : folds)
docDisplay_.addFold(fold.getRange());
}
});
registerPrefs(releaseOnDismiss_, prefs_, docDisplay_);
// Initialize sourceOnSave, and keep it in sync
view_.getSourceOnSave().setValue(document.sourceOnSave(), false);
view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>()
{
public void onValueChange(ValueChangeEvent<Boolean> event)
{
docUpdateSentinel_.setSourceOnSave(
event.getValue(),
globalDisplay_.getProgressIndicator("Error Saving Setting"));
}
});
if (document.isDirty())
dirtyState_.markDirty(false);
else
dirtyState_.markClean();
docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>()
{
public void onValueChange(ValueChangeEvent<Void> event)
{
dirtyState_.markDirty(true);
}
});
docDisplay_.addFocusHandler(new FocusHandler()
{
public void onFocus(FocusEvent event)
{
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
public boolean execute()
{
if (view_.isAttached())
checkForExternalEdit();
return false;
}
}, 500);
}
});
// validate required compontents (e.g. Tex, knitr, etc.)
checkCompilePdfDependencies();
previewHtmlHelper_.verifyPrerequisites(view_, fileType_);
syncFontSize(releaseOnDismiss_, events_, view_, fontSizeManager_);
final String rTypeId = FileTypeRegistry.R.getTypeId();
releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler(
new ValueChangeHandler<Boolean>()
{
public void onValueChange(ValueChangeEvent<Boolean> evt)
{
if (fileType_.getTypeId().equals(rTypeId))
view_.adaptToFileType(fileType_);
}
}
));
releaseOnDismiss_.add(events_.addHandler(FileChangeEvent.TYPE,
new FileChangeHandler() {
@Override
public void onFileChange(FileChangeEvent event)
{
// screen out adds and events that aren't for our path
FileChange fileChange = event.getFileChange();
if (fileChange.getType() == FileChange.ADD)
return;
else if (!fileChange.getFile().getPath().equals(getPath()))
return;
// always check for changes if this is the active editor
if (commandHandlerReg_ != null)
{
checkForExternalEdit();
}
// also check for changes on modifications if we are not dirty
// note that we don't check for changes on removed files because
// this will show a confirmation dialog
else if (event.getFileChange().getType() == FileChange.MODIFIED &&
dirtyState().getValue() == false)
{
checkForExternalEdit();
}
}
}));
spelling_ = new TextEditingTargetSpelling(docDisplay_,
docUpdateSentinel_);
initStatusBar();
}
private void checkCompilePdfDependencies()
{
compilePdfHelper_.checkCompilers(view_, fileType_);
}
private void initStatusBar()
{
statusBar_ = view_.getStatusBar();
docDisplay_.addCursorChangedHandler(new CursorChangedHandler()
{
public void onCursorChanged(CursorChangedEvent event)
{
updateStatusBarPosition();
}
});
updateStatusBarPosition();
updateStatusBarLanguage();
// build file type menu dynamically (so it can change according
// to whether e.g. knitr is installed)
statusBar_.getLanguage().addMouseDownHandler(new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event)
{
// build menu with all file types - also track whether we need
// to add the current type (may be the case for types which we
// support but don't want to expose on the menu -- e.g. Rmd
// files when knitr isn't installed)
boolean addCurrentType = true;
final StatusBarPopupMenu menu = new StatusBarPopupMenu();
TextFileType[] fileTypes = fileTypeCommands_.statusBarFileTypes();
for (TextFileType type : fileTypes)
{
menu.addItem(createMenuItemForType(type));
if (addCurrentType && type.equals(fileType_))
addCurrentType = false;
}
// add the current type if isn't on the menu
if (addCurrentType)
menu.addItem(createMenuItemForType(fileType_));
// show the menu
menu.showRelativeToUpward((UIObject) statusBar_.getLanguage());
}
});
statusBar_.getScope().addMouseDownHandler(new MouseDownHandler()
{
public void onMouseDown(MouseDownEvent event)
{
// Unlike the other status bar elements, the function outliner
// needs its menu built on demand
JsArray<Scope> tree = docDisplay_.getScopeTree();
final StatusBarPopupMenu menu = new StatusBarPopupMenu();
MenuItem defaultItem = addFunctionsToMenu(
menu, tree, "", docDisplay_.getCurrentScope(), true);
if (defaultItem != null)
{
menu.selectItem(defaultItem);
Scheduler.get().scheduleFinally(new RepeatingCommand()
{
public boolean execute()
{
menu.ensureSelectedIsVisible();
return false;
}
});
}
menu.showRelativeToUpward((UIObject) statusBar_.getScope());
}
});
}
private MenuItem createMenuItemForType(final TextFileType type)
{
SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder();
labelBuilder.appendEscaped(type.getLabel());
MenuItem menuItem = new MenuItem(
labelBuilder.toSafeHtml(),
new Command()
{
public void execute()
{
docUpdateSentinel_.changeFileType(
type.getTypeId(),
new SaveProgressIndicator(null, type, null));
}
});
return menuItem;
}
private MenuItem addFunctionsToMenu(StatusBarPopupMenu menu,
final JsArray<Scope> funcs,
String indent,
Scope defaultFunction,
boolean includeNoFunctionsMessage)
{
MenuItem defaultMenuItem = null;
if (funcs.length() == 0 && includeNoFunctionsMessage)
{
MenuItem noFunctions = new MenuItem("(No functions defined)",
false,
(Command) null);
noFunctions.setEnabled(false);
noFunctions.getElement().addClassName("disabled");
menu.addItem(noFunctions);
}
for (int i = 0; i < funcs.length(); i++)
{
final Scope func = funcs.get(i);
String childIndent = indent;
if (!StringUtil.isNullOrEmpty(func.getLabel()))
{
SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder();
labelBuilder.appendHtmlConstant(indent);
labelBuilder.appendEscaped(func.getLabel());
final MenuItem menuItem = new MenuItem(
labelBuilder.toSafeHtml(),
new Command()
{
public void execute()
{
docDisplay_.navigateToPosition(toSourcePosition(func),
true);
}
});
menu.addItem(menuItem);
childIndent = indent + " ";
if (defaultFunction != null && defaultMenuItem == null &&
func.getLabel().equals(defaultFunction.getLabel()) &&
func.getPreamble().getRow() == defaultFunction.getPreamble().getRow() &&
func.getPreamble().getColumn() == defaultFunction.getPreamble().getColumn())
{
defaultMenuItem = menuItem;
}
}
MenuItem childDefaultMenuItem = addFunctionsToMenu(
menu,
func.getChildren(),
childIndent,
defaultMenuItem == null ? defaultFunction : null,
false);
if (childDefaultMenuItem != null)
defaultMenuItem = childDefaultMenuItem;
}
return defaultMenuItem;
}
private void updateStatusBarLanguage()
{
statusBar_.getLanguage().setValue(fileType_.getLabel());
boolean isR = fileType_ == FileTypeRegistry.R || fileType_.isRnw();
statusBar_.setScopeVisible(isR);
if (isR)
updateCurrentScope();
}
private void updateStatusBarPosition()
{
Position pos = docDisplay_.getCursorPosition();
statusBar_.getPosition().setValue((pos.getRow() + 1) + ":" +
(pos.getColumn() + 1));
updateCurrentScope();
}
private void updateCurrentScope()
{
Scheduler.get().scheduleDeferred(
new ScheduledCommand()
{
public void execute()
{
Scope function = docDisplay_.getCurrentScope();
String label = function != null
? function.getLabel()
: null;
statusBar_.getScope().setValue(label);
if (function != null)
{
boolean useChunk =
function.isChunk() ||
(fileType_.isRnw() && function.isTopLevel());
if (useChunk)
statusBar_.setScopeType(StatusBar.SCOPE_CHUNK);
else if (function.isSection())
statusBar_.setScopeType(StatusBar.SCOPE_SECTION);
else
statusBar_.setScopeType(StatusBar.SCOPE_FUNCTION);
}
}
});
}
private String getNameFromDocument(SourceDocument document,
Provider<String> defaultNameProvider)
{
if (document.getPath() != null)
return FileSystemItem.getNameFromPath(document.getPath());
String name = document.getProperties().getString("tempName");
if (!StringUtil.isNullOrEmpty(name))
return name;
String defaultName = defaultNameProvider.get();
docUpdateSentinel_.setProperty("tempName", defaultName, null);
return defaultName;
}
public long getFileSizeLimit()
{
return 5 * 1024 * 1024;
}
public long getLargeFileSize()
{
return Desktop.isDesktop() ? 1024 * 1024 : 512 * 1024;
}
public void insertCode(String source, boolean blockMode)
{
docDisplay_.insertCode(source, blockMode);
}
public HashSet<AppCommand> getSupportedCommands()
{
return fileType_.getSupportedCommands(commands_);
}
public void focus()
{
docDisplay_.focus();
}
public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler)
{
return view_.addEnsureVisibleHandler(handler);
}
public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler)
{
return handlers_.addHandler(CloseEvent.getType(), handler);
}
public void fireEvent(GwtEvent<?> event)
{
handlers_.fireEvent(event);
}
public void onActivate()
{
// IMPORTANT NOTE: most of this logic is duplicated in
// CodeBrowserEditingTarget (no straightforward way to create a
// re-usable implementation) so changes here need to be synced
// If we're already hooked up for some reason, unhook.
// This shouldn't happen though.
if (commandHandlerReg_ != null)
{
Debug.log("Warning: onActivate called twice without intervening onDeactivate");
commandHandlerReg_.removeHandler();
commandHandlerReg_ = null;
}
commandHandlerReg_ = commandBinder.bind(commands_, this);
Scheduler.get().scheduleFinally(new ScheduledCommand()
{
public void execute()
{
// This has to be executed in a scheduleFinally because
// Source.manageCommands gets called after this.onActivate,
// and if we're going from a non-editor (like data view) to
// an editor, setEnabled(true) will be called on the command
// in manageCommands.
commands_.reopenSourceDocWithEncoding().setEnabled(
docUpdateSentinel_.getPath() != null);
}
});
view_.onActivate();
}
public void onDeactivate()
{
// IMPORTANT NOTE: most of this logic is duplicated in
// CodeBrowserEditingTarget (no straightforward way to create a
// re-usable implementation) so changes here need to be synced
externalEditCheckInvalidation_.invalidate();
commandHandlerReg_.removeHandler();
commandHandlerReg_ = null;
// switching tabs is a navigation action
try
{
docDisplay_.recordCurrentNavigationPosition();
}
catch(Exception e)
{
Debug.log("Exception recording nav position: " + e.toString());
}
}
@Override
public void onInitiallyLoaded()
{
checkForExternalEdit();
}
public boolean onBeforeDismiss()
{
Command closeCommand = new Command() {
public void execute()
{
CloseEvent.fire(TextEditingTarget.this, null);
}
};
if (dirtyState_.getValue())
saveWithPrompt(closeCommand, null);
else
closeCommand.execute();
return false;
}
public void save(Command onCompleted)
{
saveThenExecute(null, CommandUtil.join(sourceOnSaveCommandIfApplicable(),
onCompleted));
}
public void saveWithPrompt(final Command command, final Command onCancelled)
{
view_.ensureVisible();
globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING,
getName().getValue() + " - Unsaved Changes",
"The document '" + getName().getValue() +
"' has unsaved changes.\n\n" +
"Do you want to save these changes?",
true,
new Operation() {
public void execute() { saveThenExecute(null, command); }
},
new Operation() {
public void execute() { command.execute(); }
},
new Operation() {
public void execute() {
if (onCancelled != null)
onCancelled.execute();
}
},
"Save",
"Don't Save",
true);
}
public void revertChanges(Command onCompleted)
{
docUpdateSentinel_.revert(onCompleted);
}
private void saveThenExecute(String encodingOverride, final Command command)
{
checkCompilePdfDependencies();
final String path = docUpdateSentinel_.getPath();
if (path == null)
{
saveNewFile(null, encodingOverride, command);
return;
}
withEncodingRequiredUnlessAscii(
encodingOverride,
new CommandWithArg<String>()
{
public void execute(String encoding)
{
docUpdateSentinel_.save(path,
null,
encoding,
new SaveProgressIndicator(
FileSystemItem.createFile(path),
null,
command
));
}
});
}
private void saveNewFile(final String suggestedPath,
String encodingOverride,
final Command executeOnSuccess)
{
withEncodingRequiredUnlessAscii(
encodingOverride,
new CommandWithArg<String>()
{
public void execute(String encoding)
{
saveNewFileWithEncoding(suggestedPath,
encoding,
executeOnSuccess);
}
});
}
private void withEncodingRequiredUnlessAscii(
final String encodingOverride,
final CommandWithArg<String> command)
{
final String encoding = StringUtil.firstNotNullOrEmpty(new String[] {
encodingOverride,
docUpdateSentinel_.getEncoding(),
prefs_.defaultEncoding().getValue()
});
if (StringUtil.isNullOrEmpty(encoding))
{
if (docUpdateSentinel_.isAscii())
{
// Don't bother asking when it's just ASCII
command.execute(null);
}
else
{
withChooseEncoding(session_.getSessionInfo().getSystemEncoding(),
new CommandWithArg<String>()
{
public void execute(String newEncoding)
{
command.execute(newEncoding);
}
});
}
}
else
{
command.execute(encoding);
}
}
private void withChooseEncoding(final String defaultEncoding,
final CommandWithArg<String> command)
{
view_.ensureVisible();;
server_.iconvlist(new SimpleRequestCallback<IconvListResult>()
{
@Override
public void onResponseReceived(IconvListResult response)
{
// Stupid compiler. Use this Value shim to make the dialog available
// in its own handler.
final HasValue<ChooseEncodingDialog> d = new Value<ChooseEncodingDialog>(null);
d.setValue(new ChooseEncodingDialog(
response.getCommon(),
response.getAll(),
defaultEncoding,
false,
true,
new OperationWithInput<String>()
{
public void execute(String newEncoding)
{
if (newEncoding == null)
return;
if (d.getValue().isSaveAsDefault())
{
prefs_.defaultEncoding().setGlobalValue(newEncoding);
prefs_.writeUIPrefs();
}
command.execute(newEncoding);
}
}));
d.getValue().showModal();
}
});
}
private void saveNewFileWithEncoding(String suggestedPath,
final String encoding,
final Command executeOnSuccess)
{
view_.ensureVisible();
FileSystemItem fsi = suggestedPath != null
? FileSystemItem.createFile(suggestedPath)
: workbenchContext_.getDefaultFileDialogDir();
fileDialogs_.saveFile(
"Save File - " + getName().getValue(),
fileContext_,
fsi,
fileType_.getDefaultExtension(),
false,
new ProgressOperationWithInput<FileSystemItem>()
{
public void execute(final FileSystemItem saveItem,
ProgressIndicator indicator)
{
if (saveItem == null)
return;
try
{
workbenchContext_.setDefaultFileDialogDir(
saveItem.getParentPath());
TextFileType fileType =
fileTypeRegistry_.getTextTypeForFile(saveItem);
docUpdateSentinel_.save(
saveItem.getPath(),
fileType.getTypeId(),
encoding,
new SaveProgressIndicator(saveItem,
fileType,
executeOnSuccess));
events_.fireEvent(
new SourceFileSavedEvent(saveItem.getPath()));
}
catch (Exception e)
{
indicator.onError(e.toString());
return;
}
indicator.onCompleted();
}
});
}
public void onDismiss()
{
docUpdateSentinel_.stop();
if (spelling_ != null)
spelling_.onDismiss();
while (releaseOnDismiss_.size() > 0)
releaseOnDismiss_.remove(0).removeHandler();
if (lastExecutedCode_ != null)
{
lastExecutedCode_.detach();
lastExecutedCode_ = null;
}
}
public ReadOnlyValue<Boolean> dirtyState()
{
return dirtyState_;
}
@Override
public boolean isSaveCommandActive()
{
return
// standard check of dirty state
(dirtyState().getValue() == true) ||
// empty untitled document (allow for immediate save)
((getPath() == null) && docDisplay_.getCode().isEmpty()) ||
// source on save is active
(fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave());
}
public Widget asWidget()
{
return (Widget) view_;
}
public String getId()
{
return id_;
}
public HasValue<String> getName()
{
return name_;
}
public String getTitle()
{
return getName().getValue();
}
public String getPath()
{
return docUpdateSentinel_.getPath();
}
public String getContext()
{
return null;
}
public ImageResource getIcon()
{
return fileType_.getDefaultIcon();
}
public String getTabTooltip()
{
return getPath();
}
@Handler
void onCheckSpelling()
{
spelling_.checkSpelling();
}
@Handler
void onDebugForceTopsToZero()
{
view_.debug_forceTopsToZero();
}
@Handler
void onDebugDumpContents()
{
view_.debug_dumpContents();
}
@Handler
void onDebugImportDump()
{
view_.debug_importDump();
}
@Handler
void onReopenSourceDocWithEncoding()
{
withChooseEncoding(
docUpdateSentinel_.getEncoding(),
new CommandWithArg<String>()
{
public void execute(String encoding)
{
docUpdateSentinel_.reopenWithEncoding(encoding);
}
});
}
@Handler
void onSaveSourceDoc()
{
saveThenExecute(null, sourceOnSaveCommandIfApplicable());
}
@Handler
void onSaveSourceDocAs()
{
saveNewFile(docUpdateSentinel_.getPath(),
null,
sourceOnSaveCommandIfApplicable());
}
@Handler
void onSaveSourceDocWithEncoding()
{
withChooseEncoding(
StringUtil.firstNotNullOrEmpty(new String[] {
docUpdateSentinel_.getEncoding(),
prefs_.defaultEncoding().getValue(),
session_.getSessionInfo().getSystemEncoding()
}),
new CommandWithArg<String>()
{
public void execute(String encoding)
{
saveThenExecute(encoding, sourceOnSaveCommandIfApplicable());
}
});
}
@Handler
void onPrintSourceDoc()
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
public void execute()
{
docDisplay_.print();
}
});
}
@Handler
void onVcsFileDiff()
{
events_.fireEvent(new ShowVcsDiffEvent(
FileSystemItem.createFile(docUpdateSentinel_.getPath())));
}
@Handler
void onVcsFileLog()
{
events_.fireEvent(new ShowVcsHistoryEvent(
FileSystemItem.createFile(docUpdateSentinel_.getPath())));
}
@Handler
void onVcsFileRevert()
{
events_.fireEvent(new VcsRevertFileEvent(
FileSystemItem.createFile(docUpdateSentinel_.getPath())));
}
@Handler
void onExtractFunction()
{
docDisplay_.focus();
String initialSelection = docDisplay_.getSelectionValue();
if (initialSelection == null || initialSelection.trim().length() == 0)
{
globalDisplay_.showErrorMessage("Extract Function",
"Please select the code to extract " +
"into a function.");
return;
}
docDisplay_.fitSelectionToLines(false);
final String code = docDisplay_.getSelectionValue();
if (code == null || code.trim().length() == 0)
{
globalDisplay_.showErrorMessage("Extract Function",
"Please select the code to extract " +
"into a function.");
return;
}
Pattern leadingWhitespace = Pattern.create("^(\\s*)");
Match match = leadingWhitespace.match(code, 0);
final String indentation = match == null ? "" : match.getGroup(1);
server_.detectFreeVars(code, new ServerRequestCallback<JsArrayString>()
{
@Override
public void onResponseReceived(final JsArrayString response)
{
doExtract(response);
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showYesNoMessage(
GlobalDisplay.MSG_WARNING,
"Extract Function",
"The selected code could not be " +
"parsed.\n\n" +
"Are you sure you want to continue?",
new Operation()
{
public void execute()
{
doExtract(null);
}
},
false);
}
private void doExtract(final JsArrayString response)
{
globalDisplay_.promptForText(
"Extract Function",
"Function Name",
"",
new OperationWithInput<String>()
{
public void execute(String input)
{
String prefix = docDisplay_.getSelectionOffset(true) == 0
? "" : "\n";
String args = response != null ? response.join(", ")
: "";
docDisplay_.replaceSelection(
prefix
+ indentation
+ input.trim()
+ " <- "
+ "function (" + args + ") {\n"
+ StringUtil.indent(code, " ")
+ "\n"
+ indentation
+ "}");
}
});
}
});
}
@Handler
void onCommentUncomment()
{
if (isCursorInTexMode())
doCommentUncomment('%');
else
doCommentUncomment('
}
private void doCommentUncomment(char c)
{
docDisplay_.fitSelectionToLines(true);
String selection = docDisplay_.getSelectionValue();
// If any line's first non-whitespace character is not #, then the whole
// selection should be commented. Exception: If the whole selection is
// whitespace, then we comment out the whitespace.
Match match = Pattern.create("^\\s*[^" + c + "\\s]").match(selection, 0);
boolean uncomment = match == null && selection.trim().length() != 0;
if (uncomment)
selection = selection.replaceAll("((^|\\n)\\s*)" + c + " ?", "$1");
else
{
selection = c + " " + selection.replaceAll("\\n", "\n" + c + " ");
// If the selection ends at the very start of a line, we don't want
// to comment out that line. This enables Shift+DownArrow to select
// one line at a time.
if (selection.endsWith("\n" + c + " "))
selection = selection.substring(0, selection.length() - 2);
}
docDisplay_.replaceSelection(selection);
}
@Handler
void onReindent()
{
docDisplay_.reindent();
docDisplay_.focus();
}
@Handler
void onReflowComment()
{
docDisplay_.focus();
InputEditorSelection originalSelection = docDisplay_.getSelection();
InputEditorSelection selection = originalSelection;
if (selection.isEmpty())
{
selection = selection.growToIncludeLines("^\\s*
}
else
{
selection = selection.shrinkToNonEmptyLines();
selection = selection.extendToLineStart();
selection = selection.extendToLineEnd();
}
if (selection.isEmpty())
return;
reflowComments(selection, originalSelection.isEmpty() ?
originalSelection.getStart() :
null);
}
private Position selectionToPosition(InputEditorPosition pos)
{
return docDisplay_.selectionToPosition(pos);
}
private void reflowComments(InputEditorSelection selection,
final InputEditorPosition cursorPos)
{
String code = docDisplay_.getCode(selection);
String[] lines = code.split("\n");
String prefix = StringUtil.getCommonPrefix(lines, true);
Pattern pattern = Pattern.create("^\\s*
Match match = pattern.match(prefix, 0);
// Selection includes non-comments? Abort.
if (match == null)
return;
prefix = match.getValue();
final boolean roxygen = match.hasGroup(1);
int cursorRowIndex = 0;
int cursorColIndex = 0;
if (cursorPos != null)
{
cursorRowIndex = selectionToPosition(cursorPos).getRow() -
selectionToPosition(selection.getStart()).getRow();
cursorColIndex =
Math.max(0, cursorPos.getPosition() - prefix.length());
}
final WordWrapCursorTracker wwct = new WordWrapCursorTracker(
cursorRowIndex, cursorColIndex);
int maxLineLength =
prefs_.printMarginColumn().getValue() - prefix.length();
WordWrap wordWrap = new WordWrap(maxLineLength, false)
{
@Override
protected boolean forceWrapBefore(String line)
{
String trimmed = line.trim();
if (roxygen && trimmed.startsWith("@") && !trimmed.startsWith("@@"))
{
// Roxygen tags always need to be at the start of a line. If
// there is content immediately following the roxygen tag, then
// content should be wrapped until the next roxygen tag is
// encountered.
indent_ = "";
if (TAG_WITH_CONTENTS.match(line, 0) != null)
{
indentRestOfLines_ = true;
}
return true;
}
return super.forceWrapBefore(line);
}
@Override
protected void onChunkWritten(String chunk,
int insertionRow,
int insertionCol,
int indexInOriginalString)
{
if (indentRestOfLines_)
{
indentRestOfLines_ = false;
indent_ = " "; // TODO: Use real indent from settings
}
wwct.onChunkWritten(chunk, insertionRow, insertionCol,
indexInOriginalString);
}
private boolean indentRestOfLines_ = false;
private Pattern TAG_WITH_CONTENTS = Pattern.create("@\\w+\\s+[^\\s]");
};
for (String line : lines)
{
String content = line.substring(Math.min(line.length(),
prefix.length()));
if (content.matches("^\\s*\\@examples\\b.*$"))
wordWrap.setWrappingEnabled(false);
else if (content.trim().startsWith("@"))
wordWrap.setWrappingEnabled(true);
wwct.onBeginInputRow();
wordWrap.appendLine(content);
}
String wrappedString = wordWrap.getOutput();
StringBuilder finalOutput = new StringBuilder();
for (String line : StringUtil.getLineIterator(wrappedString))
finalOutput.append(prefix).append(line).append("\n");
// Remove final \n
if (finalOutput.length() > 0)
finalOutput.deleteCharAt(finalOutput.length()-1);
String reflowed = finalOutput.toString();
docDisplay_.setSelection(selection);
if (!reflowed.equals(code))
{
docDisplay_.replaceSelection(reflowed);
}
if (cursorPos != null)
{
if (wwct.getResult() != null)
{
int row = wwct.getResult().getY();
int col = wwct.getResult().getX();
row += selectionToPosition(selection.getStart()).getRow();
col += prefix.length();
Position pos = Position.create(row, col);
docDisplay_.setSelection(docDisplay_.createSelection(pos, pos));
}
else
{
docDisplay_.collapseSelection(false);
}
}
}
@Handler
void onExecuteCode()
{
docDisplay_.focus();
Range selectionRange = docDisplay_.getSelectionRange();
if (selectionRange.isEmpty())
{
int row = docDisplay_.getSelectionStart().getRow();
selectionRange = Range.fromPoints(
Position.create(row, 0),
Position.create(row, docDisplay_.getLength(row)));
// TODO: This should skip to next line of R code in Sweave docs
docDisplay_.moveSelectionToNextLine(true);
}
executeRange(selectionRange);
}
private void executeRange(Range range)
{
Scope sweaveChunk = scopeHelper_.getCurrentSweaveChunk(range.getStart());
String code = sweaveChunk != null
? scopeHelper_.getSweaveChunkText(sweaveChunk, range)
: docDisplay_.getCode(range.getStart(), range.getEnd());
setLastExecuted(range.getStart(), range.getEnd());
events_.fireEvent(new SendToConsoleEvent(code, true));
}
private void setLastExecuted(Position start, Position end)
{
if (lastExecutedCode_ != null)
{
lastExecutedCode_.detach();
lastExecutedCode_ = null;
}
lastExecutedCode_ = docDisplay_.createAnchoredSelection(start, end);
}
@Handler
void onExecuteAllCode()
{
sourceActiveDocument(true);
}
@Handler
void onExecuteToCurrentLine()
{
docDisplay_.focus();
int row = docDisplay_.getSelectionEnd().getRow();
int col = docDisplay_.getLength(row);
executeRange(Range.fromPoints(Position.create(0, 0),
Position.create(row, col)));
}
@Handler
void onExecuteFromCurrentLine()
{
docDisplay_.focus();
int startRow = docDisplay_.getSelectionStart().getRow();
int startColumn = 0;
int endRow = Math.max(0, docDisplay_.getRowCount() - 1);
int endColumn = docDisplay_.getLength(endRow);
Position start = Position.create(startRow, startColumn);
Position end = Position.create(endRow, endColumn);
executeRange(Range.fromPoints(start, end));
}
@Handler
void onExecuteCurrentFunction()
{
docDisplay_.focus();
// HACK: This is just to force the entire function tree to be built.
// It's the easiest way to make sure getCurrentScope() returns
// a Scope with an end.
docDisplay_.getScopeTree();
Scope currentFunction = docDisplay_.getCurrentFunction();
// Check if we're at the top level (i.e. not in a function), or in
// an unclosed function
if (currentFunction == null || currentFunction.getEnd() == null)
return;
Position start = currentFunction.getPreamble();
Position end = currentFunction.getEnd();
executeRange(Range.fromPoints(start, end));
}
@Handler
void onInsertChunk()
{
Position pos = moveCursorToNextInsertLocation();
docDisplay_.insertCode("<<>>=\n\n@\n", false);
docDisplay_.setCursorPosition(Position.create(pos.getRow(), 2));
docDisplay_.focus();
}
@Handler
void onInsertSection()
{
globalDisplay_.promptForText(
"Insert Section",
"Section label:",
"",
new OperationWithInput<String>() {
@Override
public void execute(String label)
{
// move cursor to next insert location
Position pos = moveCursorToNextInsertLocation();
// truncate length to print margin - 5
int printMarginColumn = prefs_.printMarginColumn().getValue();
int length = printMarginColumn - 5;
// truncate label to maxLength - 10 (but always allow at
// least 20 chars for the label)
int maxLabelLength = length - 10;
maxLabelLength = Math.max(maxLabelLength, 20);
if (label.length() > maxLabelLength)
label = label.substring(0, maxLabelLength-1);
// prefix
String prefix = "# " + label + " ";
// fill to maxLength (bit ensure at least 4 fill characters
// so the section parser is sure to pick it up)
StringBuffer sectionLabel = new StringBuffer();
sectionLabel.append("\n");
sectionLabel.append(prefix);
int fillChars = length - prefix.length();
fillChars = Math.max(fillChars, 4);
for (int i=0; i<fillChars; i++)
sectionLabel.append("-");
sectionLabel.append("\n\n");
// insert code and move cursor
docDisplay_.insertCode(sectionLabel.toString(), false);
docDisplay_.setCursorPosition(Position.create(pos.getRow() + 3,
0));
docDisplay_.focus();
}
});
}
private Position moveCursorToNextInsertLocation()
{
docDisplay_.collapseSelection(true);
if (!docDisplay_.moveSelectionToBlankLine())
{
int lastRow = docDisplay_.getRowCount();
int lastCol = docDisplay_.getLength(lastRow);
Position endPos = Position.create(lastRow, lastCol);
docDisplay_.setCursorPosition(endPos);
docDisplay_.insertCode("\n", false);
}
return docDisplay_.getCursorPosition();
}
@Handler
void onExecuteCurrentChunk()
{
executeSweaveChunk(scopeHelper_.getCurrentSweaveChunk(), false);
}
@Handler
void onExecuteNextChunk()
{
executeSweaveChunk(scopeHelper_.getNextSweaveChunk(), true);
}
private void executeSweaveChunk(Scope chunk, boolean scrollNearTop)
{
if (chunk == null)
return;
Range range = scopeHelper_.getSweaveChunkInnerRange(chunk);
if (scrollNearTop)
{
docDisplay_.navigateToPosition(
SourcePosition.create(range.getStart().getRow(),
range.getStart().getColumn()),
true);
}
docDisplay_.setSelection(
docDisplay_.createSelection(range.getStart(), range.getEnd()));
if (!range.isEmpty())
{
setLastExecuted(range.getStart(), range.getEnd());
String code = scopeHelper_.getSweaveChunkText(chunk);
events_.fireEvent(new SendToConsoleEvent(code, true));
docDisplay_.collapseSelection(true);
}
}
@Handler
void onJumpTo()
{
statusBar_.getScope().click();
}
@Handler
void onGoToLine()
{
globalDisplay_.promptForInteger(
"Go to Line",
"Enter line number:",
null,
new ProgressOperationWithInput<Integer>()
{
@Override
public void execute(Integer line, ProgressIndicator indicator)
{
indicator.onCompleted();
line = Math.max(1, line);
line = Math.min(docDisplay_.getRowCount(), line);
docDisplay_.navigateToPosition(
SourcePosition.create(line-1, 0),
true);
}
},
null);
}
@Handler
void onGoToFunctionDefinition()
{
docDisplay_.goToFunctionDefinition();
}
@Handler
public void onSetWorkingDirToActiveDoc()
{
// get path
String activeDocPath = docUpdateSentinel_.getPath();
if (activeDocPath != null)
{
FileSystemItem wdPath =
FileSystemItem.createFile(activeDocPath).getParentPath();
consoleDispatcher_.executeSetWd(wdPath, true);
}
else
{
globalDisplay_.showMessage(
MessageDialog.WARNING,
"Source File Not Saved",
"The currently active source file is not saved so doesn't " +
"have a directory to change into.");
return;
}
}
@SuppressWarnings("unused")
private String stangle(String sweaveStr)
{
ScopeList chunks = new ScopeList(docDisplay_);
chunks.selectAll(ScopeList.CHUNK);
StringBuilder code = new StringBuilder();
for (Scope chunk : chunks)
{
String text = scopeHelper_.getSweaveChunkText(chunk);
code.append(text);
if (text.length() > 0 && text.charAt(text.length()-1) != '\n')
code.append('\n');
}
return code.toString();
}
@Handler
void onSourceActiveDocument()
{
sourceActiveDocument(false);
}
@Handler
void onSourceActiveDocumentWithEcho()
{
sourceActiveDocument(true);
}
private void sourceActiveDocument(final boolean echo)
{
docDisplay_.focus();
String code = docDisplay_.getCode();
if (code != null && code.trim().length() > 0)
{
// R 2.14 prints a warning when sourcing a file with no trailing \n
if (!code.endsWith("\n"))
code = code + "\n";
boolean sweave =
fileType_.canCompilePDF() || fileType_.canKnitToHTML();
final boolean isKnitr = fileType_.canKnitToHTML();
String rnwWeave = isKnitr ? "knitr" :
compilePdfHelper_.getActiveRnwWeaveName();
// NOTE: we always set echo to true for knitr because knitr doesn't
// require print statements so if you don't echo to the console
// then you don't see any of the output
if (dirtyState_.getValue() || sweave)
{
server_.saveActiveDocument(code,
sweave,
rnwWeave,
new SimpleRequestCallback<Void>() {
@Override
public void onResponseReceived(Void response)
{
consoleDispatcher_.executeSourceCommand(
"~/.active-rstudio-document",
"UTF-8",
activeCodeIsAscii(),
isKnitr ? true : echo);
}
});
}
else
{
consoleDispatcher_.executeSourceCommand(getPath(),
docUpdateSentinel_.getEncoding(),
activeCodeIsAscii(),
isKnitr ? true : echo);
}
}
// update pref if necessary
if (prefs_.sourceWithEcho().getValue() != echo)
{
prefs_.sourceWithEcho().setGlobalValue(echo, true);
prefs_.writeUIPrefs();
}
}
private boolean activeCodeIsAscii()
{
String code = docDisplay_.getCode();
for (int i=0; i< code.length(); i++)
{
if (code.charAt(i) > 127)
return false;
}
return true;
}
@Handler
void onExecuteLastCode()
{
docDisplay_.focus();
if (lastExecutedCode_ != null)
{
String code = lastExecutedCode_.getValue();
if (code != null && code.trim().length() > 0)
{
events_.fireEvent(new SendToConsoleEvent(code, true));
}
}
}
@Handler
void onMarkdownHelp()
{
events_.fireEvent(new ShowHelpEvent("help/doc/markdown_help.htm")) ;
}
@Handler
void onKnitToHTML()
{
onPreviewHTML();
}
@Handler
void onPreviewHTML()
{
// validate pre-reqs
if (!previewHtmlHelper_.verifyPrerequisites(view_, fileType_))
return;
// build params
final HTMLPreviewParams params = HTMLPreviewParams.create(
docUpdateSentinel_.getPath(),
docUpdateSentinel_.getEncoding(),
fileType_.isMarkdown(),
fileType_.requiresKnit());
// command to show the preview window
final Command showPreviewWindowCommand = new Command() {
@Override
public void execute()
{
events_.fireEvent(new ShowHTMLPreviewEvent(params));
}
};
// command to run the preview
final Command runPreviewCommand = new Command() {
@Override
public void execute()
{
server_.previewHTML(params, new SimpleRequestCallback<Boolean>());
}
};
// if the document is new and unsaved, then resolve that and then
// show the preview window -- it won't activate in web mode
// due to popup activation rules but at least it will show up
if (isNewDoc())
{
saveThenExecute(null, CommandUtil.join(showPreviewWindowCommand,
runPreviewCommand));
}
// otherwise if it's dirty then show the preview window first (to
// beat the popup blockers) then save & run
else if (dirtyState().getValue())
{
showPreviewWindowCommand.execute();
saveThenExecute(null, runPreviewCommand);
}
// otherwise show the preview window then run the preview
else
{
showPreviewWindowCommand.execute();
runPreviewCommand.execute();
}
}
@Handler
void onCompilePDF()
{
String pdfPreview = prefs_.pdfPreview().getValue();
boolean showPdf = !pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_NONE);
boolean useInternalPreview =
pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_RSTUDIO) &&
session_.getSessionInfo().isInternalPdfPreviewEnabled();
Command onBeforeCompile = null;
if (useInternalPreview)
{
onBeforeCompile = new Command() {
@Override
public void execute()
{
events_.fireEvent(new ShowPDFViewerEvent());
}
};
}
String action = new String();
if (showPdf && !useInternalPreview)
action = "view_external";
handlePdfCommand(action, useInternalPreview, onBeforeCompile);
}
@Handler
void onSynctexSearch()
{
doSynctexSearch(true);
}
private void doSynctexSearch(boolean fromClick)
{
SourceLocation sourceLocation = getSelectionAsSourceLocation(fromClick);
if (sourceLocation == null)
return;
synctex_.forwardSearch(sourceLocation);
}
private SourceLocation getSelectionAsSourceLocation(boolean fromClick)
{
// get doc path (bail if the document is unsaved)
String file = docUpdateSentinel_.getPath();
if (file == null)
return null;
Position selPos = docDisplay_.getSelectionStart();
int line = selPos.getRow() + 1;
int column = selPos.getColumn() + 1;
return SourceLocation.create(file, line, column, fromClick);
}
@Handler
void onFindReplace()
{
view_.showFindReplace();
}
@Handler
void onFold()
{
Range range = Range.fromPoints(docDisplay_.getSelectionStart(),
docDisplay_.getSelectionEnd());
if (range.isEmpty())
{
// If no selection, fold the innermost non-anonymous scope
ScopeList scopeList = new ScopeList(docDisplay_);
scopeList.removeAll(ScopeList.ANON_BRACE);
Scope scope = scopeList.findLast(new ContainsPredicate(
Range.fromPoints(docDisplay_.getSelectionStart(),
docDisplay_.getSelectionEnd())));
if (scope == null)
return;
docDisplay_.addFoldFromRow(scope.getPreamble().getRow());
}
else
{
// If selection, fold the selection
docDisplay_.addFold(range);
}
}
@Handler
void onUnfold()
{
Range range = Range.fromPoints(docDisplay_.getSelectionStart(),
docDisplay_.getSelectionEnd());
if (range.isEmpty())
{
// If no selection, unfold the closest fold on the current row
Position pos = range.getStart();
AceFold startCandidate = null;
AceFold endCandidate = null;
for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds()))
{
if (startCandidate == null
&& f.getStart().getRow() == pos.getRow()
&& f.getStart().getColumn() >= pos.getColumn())
{
startCandidate = f;
}
if (f.getEnd().getRow() == pos.getRow()
&& f.getEnd().getColumn() <= pos.getColumn())
{
endCandidate = f;
}
}
if (startCandidate == null ^ endCandidate == null)
{
docDisplay_.unfold(startCandidate != null ? startCandidate
: endCandidate);
}
else if (startCandidate != null)
{
// Both are candidates; see which is closer
int startDelta = startCandidate.getStart().getColumn() - pos.getColumn();
int endDelta = pos.getColumn() - endCandidate.getEnd().getColumn();
docDisplay_.unfold(startDelta <= endDelta? startCandidate
: endCandidate);
}
}
else
{
// If selection, unfold the selection
docDisplay_.unfold(range);
}
}
@Handler
void onFoldAll()
{
// Fold all except anonymous braces
HashSet<Integer> rowsFolded = new HashSet<Integer>();
for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds()))
rowsFolded.add(f.getStart().getRow());
ScopeList scopeList = new ScopeList(docDisplay_);
scopeList.removeAll(ScopeList.ANON_BRACE);
for (Scope scope : scopeList)
{
int row = scope.getPreamble().getRow();
if (!rowsFolded.contains(row))
docDisplay_.addFoldFromRow(row);
}
}
@Handler
void onUnfoldAll()
{
for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds()))
docDisplay_.unfold(f);
}
void handlePdfCommand(final String completedAction,
final boolean useInternalPreview,
final Command onBeforeCompile)
{
if (fileType_.isRnw() && prefs_.alwaysEnableRnwConcordance().getValue())
compilePdfHelper_.ensureRnwConcordance();
// if the document has been previously saved then we should execute
// the onBeforeCompile command immediately
if (!isNewDoc() && (onBeforeCompile != null))
onBeforeCompile.execute();
saveThenExecute(null, new Command()
{
public void execute()
{
// if this was a new doc then we still need to execute the
// onBeforeCompile command
if (isNewDoc() && (onBeforeCompile != null))
onBeforeCompile.execute();
String path = docUpdateSentinel_.getPath();
if (path != null)
fireCompilePdfEvent(path, completedAction, useInternalPreview);
}
});
}
private void fireCompilePdfEvent(String path,
String completedAction,
boolean useInternalPreview)
{
// first validate the path to make sure it doesn't contain spaces
FileSystemItem file = FileSystemItem.createFile(path);
if (file.getName().indexOf(' ') != -1)
{
globalDisplay_.showErrorMessage(
"Invalid Filename",
"The file '" + file.getName() + "' cannot be compiled to " +
"a PDF because TeX does not understand paths with spaces. " +
"If you rename the file to remove spaces then " +
"PDF compilation will work correctly.");
return;
}
CompilePdfEvent event = new CompilePdfEvent(
file,
getSelectionAsSourceLocation(false),
completedAction,
useInternalPreview);
events_.fireEvent(event);
}
private Command sourceOnSaveCommandIfApplicable()
{
return new Command()
{
public void execute()
{
if (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave())
{
consoleDispatcher_.executeSourceCommand(
docUpdateSentinel_.getPath(),
docUpdateSentinel_.getEncoding(),
activeCodeIsAscii(),
false);
}
}
};
}
public void checkForExternalEdit()
{
if (!externalEditCheckInterval_.hasElapsed())
return;
externalEditCheckInterval_.reset();
externalEditCheckInvalidation_.invalidate();
// If the doc has never been saved, don't even bother checking
if (getPath() == null)
return;
final Token token = externalEditCheckInvalidation_.getInvalidationToken();
server_.checkForExternalEdit(
id_,
new ServerRequestCallback<CheckForExternalEditResult>()
{
@Override
public void onResponseReceived(CheckForExternalEditResult response)
{
if (token.isInvalid())
return;
if (response.isDeleted())
{
if (ignoreDeletes_)
return;
globalDisplay_.showYesNoMessage(
GlobalDisplay.MSG_WARNING,
"File Deleted",
"The file " + name_.getValue() + " has been " +
"deleted. Do you want to close this file now?",
false,
new Operation()
{
public void execute()
{
CloseEvent.fire(TextEditingTarget.this, null);
}
},
new Operation()
{
public void execute()
{
externalEditCheckInterval_.reset();
ignoreDeletes_ = true;
// Make sure it stays dirty
dirtyState_.markDirty(false);
}
},
false
);
}
else if (response.isModified())
{
ignoreDeletes_ = false; // Now we know it exists
// Use StringUtil.formatDate(response.getLastModified())?
if (!dirtyState_.getValue())
{
docUpdateSentinel_.revert();
}
else
{
externalEditCheckInterval_.reset();
globalDisplay_.showYesNoMessage(
GlobalDisplay.MSG_WARNING,
"File Changed",
"The file " + name_.getValue() + " has changed " +
"on disk. Do you want to reload the file from " +
"disk and discard your unsaved changes?",
false,
new Operation()
{
public void execute()
{
docUpdateSentinel_.revert();
}
},
new Operation()
{
public void execute()
{
externalEditCheckInterval_.reset();
docUpdateSentinel_.ignoreExternalEdit();
// Make sure it stays dirty
dirtyState_.markDirty(false);
}
},
true
);
}
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private SourcePosition toSourcePosition(Scope func)
{
Position pos = func.getPreamble();
return SourcePosition.create(pos.getRow(), pos.getColumn());
}
private boolean isCursorInTexMode()
{
if (fileType_.canCompilePDF())
{
if (fileType_.isRnw())
{
return SweaveFileType.TEX_LANG_MODE.equals(
docDisplay_.getLanguageMode(docDisplay_.getCursorPosition()));
}
else
{
return true;
}
}
else
{
return false;
}
}
private boolean isNewDoc()
{
return docUpdateSentinel_.getPath() == null;
}
// these methods are public static so that other editing targets which
// display source code (but don't inherit from TextEditingTarget) can share
// their implementation
public static void registerPrefs(
ArrayList<HandlerRegistration> releaseOnDismiss,
UIPrefs prefs,
final DocDisplay docDisplay)
{
releaseOnDismiss.add(prefs.highlightSelectedLine().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
docDisplay.setHighlightSelectedLine(arg);
}}));
releaseOnDismiss.add(prefs.highlightSelectedWord().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
docDisplay.setHighlightSelectedWord(arg);
}}));
releaseOnDismiss.add(prefs.showLineNumbers().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
docDisplay.setShowLineNumbers(arg);
}}));
releaseOnDismiss.add(prefs.useSpacesForTab().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
docDisplay.setUseSoftTabs(arg);
}}));
releaseOnDismiss.add(prefs.numSpacesForTab().bind(
new CommandWithArg<Integer>() {
public void execute(Integer arg) {
docDisplay.setTabSize(arg);
}}));
releaseOnDismiss.add(prefs.showMargin().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
docDisplay.setShowPrintMargin(arg);
}}));
releaseOnDismiss.add(prefs.printMarginColumn().bind(
new CommandWithArg<Integer>() {
public void execute(Integer arg) {
docDisplay.setPrintMarginColumn(arg);
}}));
}
public static void syncFontSize(
ArrayList<HandlerRegistration> releaseOnDismiss,
EventBus events,
final TextDisplay view,
FontSizeManager fontSizeManager)
{
releaseOnDismiss.add(events.addHandler(
ChangeFontSizeEvent.TYPE,
new ChangeFontSizeHandler()
{
public void onChangeFontSize(ChangeFontSizeEvent event)
{
view.setFontSize(event.getFontSize());
}
}));
view.setFontSize(fontSizeManager.getSize());
}
public static void onPrintSourceDoc(final DocDisplay docDisplay)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
public void execute()
{
docDisplay.print();
}
});
}
public static void addRecordNavigationPositionHandler(
ArrayList<HandlerRegistration> releaseOnDismiss,
final DocDisplay docDisplay,
final EventBus events,
final EditingTarget target)
{
releaseOnDismiss.add(docDisplay.addRecordNavigationPositionHandler(
new RecordNavigationPositionHandler() {
@Override
public void onRecordNavigationPosition(
RecordNavigationPositionEvent event)
{
SourcePosition pos = SourcePosition.create(
target.getContext(),
event.getPosition().getRow(),
event.getPosition().getColumn(),
docDisplay.getScrollTop());
events.fireEvent(new SourceNavigationEvent(
SourceNavigation.create(
target.getId(),
target.getPath(),
pos)));
}
}));
}
private StatusBar statusBar_;
private final DocDisplay docDisplay_;
private final UIPrefs prefs_;
private Display view_;
private final Commands commands_;
private SourceServerOperations server_;
private EventBus events_;
private final GlobalDisplay globalDisplay_;
private final FileDialogs fileDialogs_;
private final FileTypeRegistry fileTypeRegistry_;
private final FileTypeCommands fileTypeCommands_;
private final ConsoleDispatcher consoleDispatcher_;
private final WorkbenchContext workbenchContext_;
private final Session session_;
private final Synctex synctex_;
private final FontSizeManager fontSizeManager_;
private DocUpdateSentinel docUpdateSentinel_;
private Value<String> name_ = new Value<String>(null);
private TextFileType fileType_;
private String id_;
private HandlerRegistration commandHandlerReg_;
private ArrayList<HandlerRegistration> releaseOnDismiss_ =
new ArrayList<HandlerRegistration>();
private final DirtyState dirtyState_;
private HandlerManager handlers_ = new HandlerManager(this);
private FileSystemContext fileContext_;
private final TextEditingTargetCompilePdfHelper compilePdfHelper_;
private final TextEditingTargetPreviewHtmlHelper previewHtmlHelper_;
private boolean ignoreDeletes_;
private final TextEditingTargetScopeHelper scopeHelper_;
private TextEditingTargetSpelling spelling_;
// Allows external edit checks to supercede one another
private final Invalidation externalEditCheckInvalidation_ =
new Invalidation();
// Prevents external edit checks from happening too soon after each other
private final IntervalTracker externalEditCheckInterval_ =
new IntervalTracker(1000, true);
private AnchoredSelection lastExecutedCode_;
} |
package org.openlmis.referencedata.web;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.openlmis.referencedata.domain.RightName.ORDERABLES_MANAGE;
import static org.openlmis.referencedata.util.messagekeys.OrderableMessageKeys.ERROR_ID_MISMATCH;
import static org.openlmis.referencedata.util.messagekeys.OrderableMessageKeys.ERROR_NET_CONTENT_REQUIRED;
import static org.openlmis.referencedata.util.messagekeys.OrderableMessageKeys.ERROR_PACK_ROUNDING_THRESHOLD_REQUIRED;
import static org.openlmis.referencedata.util.messagekeys.OrderableMessageKeys.ERROR_PRODUCT_CODE_REQUIRED;
import static org.openlmis.referencedata.util.messagekeys.OrderableMessageKeys.ERROR_ROUND_TO_ZERO_REQUIRED;
import static org.openlmis.referencedata.web.BaseController.RFC_7231_FORMAT;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.jayway.restassured.response.Response;
import guru.nidi.ramltester.junit.RamlMatchers;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.apache.http.HttpStatus;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.openlmis.referencedata.PageImplRepresentation;
import org.openlmis.referencedata.domain.Code;
import org.openlmis.referencedata.domain.Dispensable;
import org.openlmis.referencedata.domain.Orderable;
import org.openlmis.referencedata.domain.OrderableDisplayCategory;
import org.openlmis.referencedata.domain.Program;
import org.openlmis.referencedata.domain.ProgramOrderable;
import org.openlmis.referencedata.domain.RightName;
import org.openlmis.referencedata.dto.OrderableDto;
import org.openlmis.referencedata.dto.ProgramOrderableDto;
import org.openlmis.referencedata.dto.VersionIdentityDto;
import org.openlmis.referencedata.exception.UnauthorizedException;
import org.openlmis.referencedata.util.Message;
import org.openlmis.referencedata.util.Pagination;
import org.openlmis.referencedata.utils.AuditLogHelper;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@SuppressWarnings({"PMD.TooManyMethods"})
public class OrderableControllerIntegrationTest extends BaseWebIntegrationTest {
private static final String RESOURCE_URL = "/api/orderables";
private static final String ID_URL = RESOURCE_URL + "/{id}";
private static final String SEARCH_URL = RESOURCE_URL + "/search";
private static final String UNIT = "unit";
private static final String NAME = "name";
private static final String CODE = "code";
private static final String PROGRAM_CODE = "program";
private static final String ID = "id";
private static final String VERSION_NAME = "versionNumber";
private static final String ZONE_ID = "UTC";
@Captor
public ArgumentCaptor<QueryOrderableSearchParams> searchParamsArgumentCaptor;
private Orderable orderable;
private OrderableDto orderableDto = new OrderableDto();
private UUID orderableId = UUID.randomUUID();
private Long orderableVersionNumber = 1L;
private ZonedDateTime modifiedDate = ZonedDateTime.now(ZoneId.of(ZONE_ID)).withNano(0);
@Before
@Override
public void setUp() {
super.setUp();
orderable = new Orderable(Code.code(CODE), Dispensable.createNew(UNIT),
10, 5, false, orderableId, orderableVersionNumber);
orderable.setProgramOrderables(Collections.emptyList());
orderable.setLastUpdated(modifiedDate);
orderable.export(orderableDto);
when(orderableRepository.save(any(Orderable.class))).thenReturn(orderable);
given(orderableRepository.findFirstByIdentityIdOrderByIdentityVersionNumberDesc(
orderable.getId())).willReturn(orderable);
}
@Test
public void shouldCreateNewOrderable() {
mockUserHasRight(ORDERABLES_MANAGE);
Response response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(200)
.extract().response();
OrderableDto orderableDtoResponse = response.as(OrderableDto.class);
assertOrderablesDtoParams(orderableDto, orderableDtoResponse);
assertEquals(orderableDto.getPrograms(), orderableDtoResponse.getPrograms());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
assertThat(response.getHeaders().hasHeaderWithName(HttpHeaders.LAST_MODIFIED), is(true));
}
@Test
public void updateShouldUpdateOrderable() {
mockUserHasRight(ORDERABLES_MANAGE);
when(orderableRepository.save(any(Orderable.class))).thenAnswer(i -> i.getArguments()[0]);
Response response1 = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(200)
.extract().response();
OrderableDto orderableDto1 = response1.as(OrderableDto.class);
orderableDto1.setNetContent(11L);
Response response2 = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto1)
.when()
.put(String.join("/", RESOURCE_URL, orderableDto1.getId().toString()))
.then()
.statusCode(200)
.extract().response();
OrderableDto orderableDto2 = response2.as(OrderableDto.class);
assertEquals(11L, orderableDto2.getNetContent().longValue());
assertEquals(orderableDto1.getId(), orderableDto2.getId());
assertNotEquals(orderableDto1, orderableDto2);
assertThat(response1.getHeaders().hasHeaderWithName(HttpHeaders.LAST_MODIFIED), is(true));
assertThat(response2.getHeaders().hasHeaderWithName(HttpHeaders.LAST_MODIFIED), is(true));
}
@Test
public void shouldUpdateSequentially() throws Exception {
int requestCount = 10; //too many requests may slow down test execution
mockUserHasRight(ORDERABLES_MANAGE);
mockDecreasingResponseTime(requestCount);
Queue<String> queue = new ConcurrentLinkedQueue<>();
ExecutorService executorService = Executors.newFixedThreadPool(java.lang.Thread.activeCount());
for (int requestNumber = 0; requestNumber < requestCount; requestNumber++) {
simulateAsyncCreateRequestAndLogToQueue(queue, executorService, requestNumber);
}
try {
executorService.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
executorService.shutdownNow();
throw ie;
}
assertEquals(requestCount, queue.size());
assertProperExecutionOrder(requestCount, queue);
executorService.shutdownNow();
}
@Test
public void updateShouldReturnBadRequestIfUrlAndDtoIdsDoNotMatch() {
mockUserHasRight(ORDERABLES_MANAGE);
checkBadRequestBody(orderableDto, ERROR_ID_MISMATCH,
String.join("/", RESOURCE_URL, UUID.randomUUID().toString()));
}
@Test
public void updateShouldReturnNotFoundIfOrderableNotFound() {
mockUserHasRight(ORDERABLES_MANAGE);
given(orderableRepository.findFirstByIdentityIdOrderByIdentityVersionNumberDesc(
orderable.getId())).willReturn(null);
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(String.join("/", RESOURCE_URL, orderableDto.getId().toString()))
.then()
.statusCode(404);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldCreateNewOrderableWithProgramOrderable() {
mockUserHasRight(ORDERABLES_MANAGE);
UUID programId = UUID.randomUUID();
Program program = new Program(programId);
OrderableDisplayCategory orderableDisplayCategory = OrderableDisplayCategory
.createNew(Code.code("orderableDisplayCategoryCode"));
orderableDisplayCategory.setId(UUID.randomUUID());
ProgramOrderable programOrderable = new ProgramOrderable(program, orderable, 1, true,
orderableDisplayCategory, true, 1, Money.of(CurrencyUnit.USD, 10.0));
orderable.setProgramOrderables(Collections.singletonList(programOrderable));
orderable.export(orderableDto);
when(programRepository.findOne(programId)).thenReturn(program);
OrderableDto response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(200)
.extract().as(OrderableDto.class);
assertOrderablesDtoParams(orderableDto, response);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldCreateNewOrderableWithIdentifiers() {
mockUserHasRight(ORDERABLES_MANAGE);
Map<String, String> identifiersMap = ImmutableMap.of(
"CommodityType", UUID.randomUUID().toString(),
"TradeItem", UUID.randomUUID().toString());
orderable.setIdentifiers(identifiersMap);
orderable.export(orderableDto);
OrderableDto response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(200)
.extract().as(OrderableDto.class);
assertOrderablesDtoParams(orderableDto, response);
assertEquals(orderableDto.getPrograms(), response.getPrograms());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldRejectPutOrderableIfUserHasNoRight() {
mockUserHasNoRight(ORDERABLES_MANAGE);
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(403);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldRejectIfProductCodeIsEmpty() {
mockUserHasRight(ORDERABLES_MANAGE);
orderableDto.setProductCode("");
checkBadRequestBody(orderableDto, ERROR_PRODUCT_CODE_REQUIRED, RESOURCE_URL);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldRejectIfPackRoundingThresholdIsNull() {
mockUserHasRight(ORDERABLES_MANAGE);
orderableDto.setPackRoundingThreshold(null);
checkBadRequestBody(orderableDto, ERROR_PACK_ROUNDING_THRESHOLD_REQUIRED, RESOURCE_URL);
}
@Test
public void shouldRejectIfRoundToZeroIsNull() {
mockUserHasRight(ORDERABLES_MANAGE);
orderableDto.setRoundToZero(null);
checkBadRequestBody(orderableDto, ERROR_ROUND_TO_ZERO_REQUIRED, RESOURCE_URL);
}
@Test
public void shouldRejectIfNetContentIsNull() {
mockUserHasRight(ORDERABLES_MANAGE);
orderableDto.setNetContent(null);
checkBadRequestBody(orderableDto, ERROR_NET_CONTENT_REQUIRED, RESOURCE_URL);
}
@Test
public void shouldRetrieveAllOrderables() {
final List<Orderable> items = Collections.singletonList(orderable);
when(orderableService
.searchOrderables(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(Pagination.getPage(items));
when(orderableService
.getLatestLastUpdatedDate(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(modifiedDate);
PageImplRepresentation response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(PageImplRepresentation.class);
checkIfEquals(response, OrderableDto.newInstance(items));
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldRetrieveAllOrderablesIfAnyResourceWasModified() {
final List<Orderable> items = Collections.singletonList(orderable);
when(orderableService
.searchOrderables(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(Pagination.getPage(items));
when(orderableService
.getLatestLastUpdatedDate(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(modifiedDate);
PageImplRepresentation response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.minusHours(1).format(RFC_7231_FORMAT))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(HttpStatus.SC_OK)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(PageImplRepresentation.class);
checkIfEquals(response, OrderableDto.newInstance(items));
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldReturnNotModifiedAndNoResponseBodyIfNoOrderableWasModified() {
final List<Orderable> items = Collections.singletonList(orderable);
when(orderableService
.searchOrderables(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(Pagination.getPage(items));
when(orderableService
.getLatestLastUpdatedDate(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(modifiedDate);
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.format(RFC_7231_FORMAT))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(HttpStatus.SC_NOT_MODIFIED)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT));
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldSearchOrderables() {
final String code = "some-code";
final String name = "some-name";
final String programCode = "program-code";
final List<Orderable> items = Collections.singletonList(orderable);
UUID orderableId2 = UUID.randomUUID();
when(orderableService
.searchOrderables(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(Pagination.getPage(items));
when(orderableService
.getLatestLastUpdatedDate(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(modifiedDate);
PageImplRepresentation response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.parameter(CODE, code)
.parameter(NAME, name)
.parameter(PROGRAM_CODE, programCode)
.parameter(ID, orderableId)
.parameter(ID, orderableId2)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(PageImplRepresentation.class);
checkIfEquals(response, OrderableDto.newInstance(items));
verify(orderableService)
.searchOrderables(searchParamsArgumentCaptor.capture(), any(Pageable.class));
QueryOrderableSearchParams value = searchParamsArgumentCaptor.getValue();
assertEquals(code, value.getCode());
assertEquals(name, value.getName());
assertEquals(programCode, value.getProgramCode());
assertEquals(new HashSet<>(Arrays.asList(orderableId, orderableId2)), value.getIds());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldPaginateSearchOrderables() {
final List<Orderable> items = Collections.singletonList(orderable);
Pageable page = new PageRequest(0, 10);
when(orderableService.searchOrderables(any(QueryOrderableSearchParams.class), eq(page)))
.thenReturn(Pagination.getPage(items, page));
when(orderableService
.getLatestLastUpdatedDate(any(QueryOrderableSearchParams.class), any(Pageable.class)))
.thenReturn(modifiedDate);
PageImplRepresentation response = restAssured
.given()
.queryParam("page", page.getPageNumber())
.queryParam("size", page.getPageSize())
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(PageImplRepresentation.class);
assertEquals(1, response.getContent().size());
assertEquals(1, response.getTotalElements());
assertEquals(1, response.getTotalPages());
assertEquals(1, response.getNumberOfElements());
assertEquals(10, response.getSize());
assertEquals(0, response.getNumber());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowPaginationWithZeroSize() {
final List<Orderable> items = Collections.singletonList(orderable);
Pageable page = new PageRequest(0, 0);
when(orderableService.searchOrderables(any(QueryOrderableSearchParams.class), eq(page)))
.thenReturn(Pagination.getPage(items, page));
restAssured
.given()
.queryParam("page", page.getPageNumber())
.queryParam("size", page.getPageSize())
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(400);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowPaginationWithoutSize() {
final List<Orderable> items = Collections.singletonList(orderable);
Pageable page = new PageRequest(0, 0);
when(orderableService.searchOrderables(any(QueryOrderableSearchParams.class), eq(page)))
.thenReturn(Pagination.getPage(items, page));
restAssured
.given()
.queryParam("page", page.getPageNumber())
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.get(RESOURCE_URL)
.then()
.statusCode(400);
}
@Test
public void shouldFindOrderableByIdentityId() {
OrderableDto response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.pathParam(ID, orderableId)
.when()
.get(ID_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(OrderableDto.class);
assertEquals(orderableId, response.getId());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldFindOrderableByIdentityIdAndVersionNumber() {
when(orderableRepository.findByIdentityIdAndIdentityVersionNumber(
orderable.getId(), orderableVersionNumber)).thenReturn(orderable);
OrderableDto response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.pathParam(ID, orderableId)
.queryParam(VERSION_NAME, orderableVersionNumber)
.when()
.get(ID_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(OrderableDto.class);
assertEquals(orderableId, response.getId());
assertEquals(orderableVersionNumber, orderable.getVersionNumber());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldReturnOrderableIfResourceWasModified() {
OrderableDto response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.minusHours(1).format(RFC_7231_FORMAT))
.pathParam(ID, orderableId)
.when()
.get(ID_URL)
.then()
.statusCode(200)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract().as(OrderableDto.class);
assertEquals(orderableId, response.getId());
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldReturnNotModifiedAndNoResponseBodyWhenResourceWasNotModified() {
when(orderableRepository.findByIdentityIdAndIdentityVersionNumber(
orderable.getId(), orderableVersionNumber)).thenReturn(orderable);
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.format(RFC_7231_FORMAT))
.pathParam(ID, orderableId)
.queryParam(VERSION_NAME, orderableVersionNumber)
.when()
.get(ID_URL)
.then()
.statusCode(304)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT));
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
// POST /orderables/search
@Test
public void shouldPostSearchOrderables() {
OrderableSearchParams searchParams = new OrderableSearchParams(
orderableDto.getProductCode(), orderableDto.getFullProductName(),
orderable.getProductCode().toString(),
Lists.newArrayList(new VersionIdentityDto(
orderableDto.getId(), orderableDto.getVersionNumber())),
0, 10);
given(orderableRepository
.search(eq(searchParams), any(Pageable.class)))
.willReturn(Pagination.getPage(Lists.newArrayList(orderable)));
given(orderableRepository
.findOrderablesWithLatestModifiedDate(eq(searchParams), any(Pageable.class)))
.willReturn(Lists.newArrayList(orderable));
PageImplRepresentation response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.body(searchParams)
.post(SEARCH_URL)
.then()
.statusCode(HttpStatus.SC_OK)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract()
.as(PageImplRepresentation.class);
assertEquals(1, response.getContent().size());
assertEquals(orderableDto.getId().toString(),
((java.util.LinkedHashMap) response.getContent().get(0)).get("id"));
}
@Test
public void shouldPostSearchOrderablesIfAnyResourceWasModified() {
OrderableSearchParams searchParams = new OrderableSearchParams(
orderableDto.getProductCode(), orderableDto.getFullProductName(),
orderable.getProductCode().toString(),
Lists.newArrayList(new VersionIdentityDto(
orderableDto.getId(), orderableDto.getVersionNumber())),
0, 10);
given(orderableRepository
.search(eq(searchParams), any(Pageable.class)))
.willReturn(Pagination.getPage(Lists.newArrayList(orderable)));
given(orderableRepository
.findOrderablesWithLatestModifiedDate(eq(searchParams), any(Pageable.class)))
.willReturn(Lists.newArrayList(orderable));
PageImplRepresentation response = restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.minusHours(1).format(RFC_7231_FORMAT))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.body(searchParams)
.post(SEARCH_URL)
.then()
.statusCode(HttpStatus.SC_OK)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT))
.extract()
.as(PageImplRepresentation.class);
assertEquals(1, response.getContent().size());
assertEquals(orderableDto.getId().toString(),
((java.util.LinkedHashMap) response.getContent().get(0)).get("id"));
}
@Test
public void shouldReturnNotModifiedAndNoResponseBodyWhenNoResourcesWereModified() {
OrderableSearchParams searchParams = new OrderableSearchParams(
orderableDto.getProductCode(), orderableDto.getFullProductName(),
orderable.getProductCode().toString(),
Lists.newArrayList(new VersionIdentityDto(
orderableDto.getId(), orderableDto.getVersionNumber())),
0, 10);
given(orderableRepository
.search(eq(searchParams), any(Pageable.class)))
.willReturn(Pagination.getPage(Lists.newArrayList(orderable)));
given(orderableRepository
.findOrderablesWithLatestModifiedDate(eq(searchParams), any(Pageable.class)))
.willReturn(Lists.newArrayList(orderable));
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.header(HttpHeaders.IF_MODIFIED_SINCE, modifiedDate.format(RFC_7231_FORMAT))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.body(searchParams)
.post(SEARCH_URL)
.then()
.statusCode(HttpStatus.SC_NOT_MODIFIED)
.header(HttpHeaders.LAST_MODIFIED, modifiedDate.format(RFC_7231_FORMAT));
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldReturnUnauthorizedIfTokenWasNotProvidedInPostSearchEndpoint() {
restAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.body(new OrderableSearchParams())
.post(SEARCH_URL)
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void getAuditLogShouldReturnNotFoundIfEntityDoesNotExist() {
doNothing()
.when(rightService)
.checkAdminRight(RightName.ORDERABLES_MANAGE);
given(orderableRepository.existsById(any(UUID.class))).willReturn(false);
AuditLogHelper.notFound(restAssured, getTokenHeader(), RESOURCE_URL);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void getAuditLogShouldReturnUnauthorizedIfUserDoesNotHaveRight() {
doThrow(new UnauthorizedException(new Message("UNAUTHORIZED")))
.when(rightService)
.checkAdminRight(RightName.ORDERABLES_MANAGE);
AuditLogHelper.unauthorized(restAssured, getTokenHeader(), RESOURCE_URL);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
@Test
public void shouldGetAuditLog() {
doNothing()
.when(rightService)
.checkAdminRight(RightName.ORDERABLES_MANAGE);
given(orderableRepository.existsById(any(UUID.class))).willReturn(true);
AuditLogHelper.ok(restAssured, getTokenHeader(), RESOURCE_URL);
assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}
private ProgramOrderableDto generateProgramOrderable() {
return new ProgramOrderableDto(UUID.randomUUID(), UUID.randomUUID(),
null, null, true, true, 0, 1, Money.of(CurrencyUnit.USD, 10.0));
}
private void checkIfEquals(PageImplRepresentation response, List<OrderableDto> expected) {
List pageContent = response.getContent();
assertEquals(expected.size(), pageContent.size());
for (int i = 0; i < pageContent.size(); i++) {
Map<String, String> retrieved = (LinkedHashMap) pageContent.get(i);
assertEquals(expected.get(i).getFullProductName(),
retrieved.get("fullProductName"));
assertEquals(expected.get(i).getProductCode(),
retrieved.get("productCode"));
assertEquals(expected.get(i).getNetContent().intValue(),
retrieved.get("netContent"));
assertEquals(expected.get(i).getPackRoundingThreshold().intValue(),
retrieved.get("packRoundingThreshold"));
assertEquals(expected.get(i).getRoundToZero(),
retrieved.get("roundToZero"));
}
}
private void simulateAsyncCreateRequestAndLogToQueue(Queue<String> queue,
ExecutorService executorService,
int requestNumber) throws Exception {
String requestIndex = String.valueOf(requestNumber);
Future future = executorService.submit(() -> {
orderableDto.setDescription(requestIndex);
restAssured
.given()
.header(HttpHeaders.AUTHORIZATION, getTokenHeader())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(orderableDto)
.when()
.put(RESOURCE_URL)
.then()
.statusCode(200)
.extract().as(OrderableDto.class);
queue.add(requestIndex);
});
future.get(); // throws exception if exception in executed task
}
private void assertProperExecutionOrder(int requestCount, Queue<String> queue) {
IntStream.range(0, requestCount).forEach(i -> assertEquals(String.valueOf(i), queue.poll()));
}
private void mockDecreasingResponseTime(int requestCount) {
when(orderableRepository.save(any(Orderable.class))).then((invocation) -> {
Orderable orderable = (Orderable) invocation.getArguments()[0];
TimeUnit.MILLISECONDS.sleep(10 * requestCount
- requestCount * Integer.valueOf(orderable.getDescription()));
return orderable;
});
}
private void assertOrderablesDtoParams(OrderableDto orderableDto, OrderableDto response) {
assertEquals(orderableDto.getProductCode(), response.getProductCode());
assertEquals(orderableDto.getDispensable(), response.getDispensable());
assertEquals(orderableDto.getFullProductName(), response.getFullProductName());
assertEquals(orderableDto.getDescription(), response.getDescription());
assertEquals(orderableDto.getNetContent(), response.getNetContent());
assertEquals(orderableDto.getPackRoundingThreshold(), response.getPackRoundingThreshold());
assertEquals(orderableDto.getRoundToZero(), response.getRoundToZero());
assertEquals(orderableDto.getChildren(), response.getChildren());
assertEquals(orderableDto.getIdentifiers(), response.getIdentifiers());
assertEquals(orderableDto.getExtraData(), response.getExtraData());
assertEquals(orderableDto.getOrderableRepository(), response.getOrderableRepository());
assertEquals(orderableDto.getVersionNumber(), response.getVersionNumber());
}
} |
package au.gov.ga.geodesy.support.mapper.dozer.populator;
import au.gov.ga.geodesy.support.utils.GMLGmlTools;
import au.gov.ga.geodesy.support.utils.GMLMiscTools;
import au.gov.xml.icsm.geodesyml.v_0_3.MoreInformationType;
import net.opengis.gml.v_3_2_1.CodeType;
public class MoreInformationTypePopulator extends GeodesyMLElementPopulator<MoreInformationType> {
/**
* Consider all required elements for this type and add any missing ones with default values.
*
* @param gnssReceiverType
*/
@Override
public void checkAllRequiredElementsPopulated(MoreInformationType moreInformationType) {
// This element can be blank when receiver hasn't been removed. Some other logic in the project
// removes empty elements from the Sopac SiteLog before it gets to this translator
checkElementPopulated(moreInformationType, "dataCenter", GMLMiscTools.getEmptyList(String.class));
checkElementPopulated(moreInformationType, "urlForMoreInformation", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "siteMap", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "siteDiagram", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "sitePictures", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "monumentDescription", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "antennaGraphicsWithDimensions", GMLMiscTools.getEmptyString());
checkElementPopulated(moreInformationType, "insertTextGraphicFromAntenna", GMLMiscTools.getEmptyString());
// TODO fix up CodeValue
CodeType codeType = GMLGmlTools.getEmptyCodeType();
codeType.setValue("CodeTypeTODO");
codeType.setCodeSpace("CodeSpaceTODO");
checkElementPopulated(moreInformationType, "DOI", codeType);
}
} |
package ca.corefacility.bioinformatics.irida.config.data;
import java.util.Properties;
import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.util.StringUtils;
@Configuration
@Profile({ "dev", "prod", "it" })
public class IridaApiJdbcDataSourceConfig implements DataConfig {
@Autowired
Environment environment;
private static final Logger logger = LoggerFactory.getLogger(IridaApiJdbcDataSourceConfig.class);
private static final String HIBERNATE_IMPORT_FILES = "hibernate.hbm2ddl.import_files";
private static final String HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
/**
* Create an instance of {@link SpringLiquibase} to update the database
* schema with liquibase change sets. This bean should only be invoked in a
* production/dev environment and should *not* be invoked if Hibernate is
* going to be creating the database schema. The scenario should not come
* up, however we will test to see if Hibernate is set to generate a schema
* before executing.
*
* @param dataSource
* the connection to use to migrate the database
* @return an instance of {@link SpringLiquibase}.
*/
@Bean
// don't bother for integration tests.
@Profile({ "dev", "prod" })
public SpringLiquibase springLiquibase(final DataSource dataSource) {
final SpringLiquibase springLiquibase = new SpringLiquibase();
springLiquibase.setDataSource(dataSource);
springLiquibase.setChangeLog("classpath:ca/corefacility/bioinformatics/irida/database/all-changes.xml");
// confirm that hibernate isn't also scheduled to execute
final String importFiles = environment.getProperty(HIBERNATE_IMPORT_FILES);
final String hbm2ddlAuto = environment.getProperty(HIBERNATE_HBM2DDL_AUTO);
Boolean liquibaseShouldRun = environment.getProperty("liquibase.update.database.schema", Boolean.class);
if (!StringUtils.isEmpty(importFiles) || !StringUtils.isEmpty(hbm2ddlAuto)) {
if (liquibaseShouldRun) {
// log that we're disabling liquibase regardless of what was
// requested in irida.conf
logger.warn("**** DISABLING LIQUIBASE ****: You have configured liquibase to execute a schema update, but Hibernate is also configured to create the schema.");
logger.warn("**** DISABLING LIQUIBASE ****: " + HIBERNATE_HBM2DDL_AUTO
+ "should be set to an empty string (or not set), but is currently set to: [" + hbm2ddlAuto
+ "]");
logger.warn("**** DISABLING LIQUIBASE ****: " + HIBERNATE_IMPORT_FILES
+ " should be set to an empty string (or not set), but is currently set to: [" + importFiles
+ "]");
}
liquibaseShouldRun = Boolean.FALSE;
}
springLiquibase.setShouldRun(liquibaseShouldRun);
springLiquibase.setIgnoreClasspathPrefix(true);
return springLiquibase;
}
@Bean
public DataSource dataSource() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
basicDataSource.setUrl(environment.getProperty("jdbc.url"));
basicDataSource.setUsername(environment.getProperty("jdbc.username"));
basicDataSource.setPassword(environment.getProperty("jdbc.password"));
basicDataSource.setInitialSize(environment.getProperty("jdbc.pool.initialSize", Integer.class));
basicDataSource.setMaxTotal(environment.getProperty("jdbc.pool.maxActive", Integer.class));
basicDataSource.setMaxWaitMillis(environment.getProperty("jdbc.pool.maxWait", Long.class));
basicDataSource.setTestOnBorrow(environment.getProperty("jdbc.pool.testOnBorrow", Boolean.class));
basicDataSource.setTestOnReturn(environment.getProperty("jdbc.pool.testOnReturn", Boolean.class));
basicDataSource.setTestWhileIdle(environment.getProperty("jdbc.pool.testWhileIdle", Boolean.class));
basicDataSource.setValidationQuery(environment.getProperty("jdbc.pool.validationQuery"));
return basicDataSource;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(false);
adapter.setGenerateDdl(true);
adapter.setDatabase(Database.MYSQL);
return adapter;
}
@Bean
public Properties getJpaProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.setProperty(HIBERNATE_HBM2DDL_AUTO, environment.getProperty(HIBERNATE_HBM2DDL_AUTO));
// if import_files is empty it tries to load any properties file it can
// find. Stopping this here.
String importFiles = environment.getProperty(HIBERNATE_IMPORT_FILES);
if (!StringUtils.isEmpty(importFiles)) {
properties.setProperty(HIBERNATE_IMPORT_FILES, importFiles);
}
properties.setProperty("org.hibernate.envers.store_data_at_delete",
environment.getProperty("org.hibernate.envers.store_data_at_delete"));
properties.setProperty("show_sql", "false");
return properties;
}
} |
package mobi.hsz.idea.gitignore.util;
import com.intellij.util.containers.ContainerUtil;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Util class to speed up and limit regex operation on the files paths.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 1.3.1
*/
public class MatcherUtil {
/** Stores calculated matching results. */
private static final HashMap<Integer, Boolean> CACHE = ContainerUtil.newHashMap();
/** Private constructor to prevent creating {@link Icons} instance. */
private MatcherUtil() {
}
/**
* Extracts alphanumeric parts from the regex pattern and checks if any of them is contained in the tested path.
* Looking for the parts speed ups the matching and prevents from running whole regex on the string.
*
* @param matcher to explode
* @param path to check
* @return path matches the pattern
*/
public static boolean match(@Nullable Matcher matcher, @Nullable String path) {
if (matcher == null || path == null) {
return false;
}
int hashCode = new HashCodeBuilder().append(matcher.pattern()).append(path).toHashCode();
if (!CACHE.containsKey(hashCode)) {
final String[] parts = getParts(matcher);
boolean result = false;
if (parts.length == 0 || matchAllParts(parts, path)) {
try {
result = matcher.reset(path).find();
} catch (StringIndexOutOfBoundsException ignored) {
}
}
CACHE.put(hashCode, result);
}
return CACHE.get(hashCode);
}
/**
* Checks if given path contains all of the path parts.
*
* @param parts that should be contained in path
* @param path to check
* @return path contains all parts
*/
public static boolean matchAllParts(@Nullable String[] parts, @Nullable String path) {
if (parts == null || path == null) {
return false;
}
int index = -1;
for (String part : parts) {
index = path.indexOf(part, index);
if (index == -1) {
return false;
}
}
return true;
}
/**
* Checks if given path contains any of the path parts.
*
* @param parts that should be contained in path
* @param path to check
* @return path contains any of the parts
*/
public static boolean matchAnyPart(@Nullable String[] parts, @Nullable String path) {
if (parts == null || path == null) {
return false;
}
for (String part : parts) {
if (path.contains(part)) {
return true;
}
}
return false;
}
/**
* Extracts alphanumeric parts from {@link Matcher} pattern.
*
* @param matcher to handle
* @return extracted parts
*/
@NotNull
public static String[] getParts(@Nullable Matcher matcher) {
if (matcher == null) {
return new String[0];
}
return getParts(matcher.pattern());
}
/**
* Extracts alphanumeric parts from {@link Pattern}.
*
* @param pattern to handle
* @return extracted parts
*/
@NotNull
public static String[] getParts(@Nullable Pattern pattern) {
if (pattern == null) {
return new String[0];
}
final List<String> parts = ContainerUtil.newArrayList();
final String sPattern = pattern.toString();
String part = "";
boolean inSquare = false;
for (int i = 0; i < sPattern.length(); i++) {
char ch = sPattern.charAt(i);
if (!inSquare && Character.isLetterOrDigit(ch)) {
part += sPattern.charAt(i);
} else if (!part.isEmpty()) {
parts.add(part);
part = "";
}
inSquare = ch != ']' && ((ch == '[') || inSquare);
}
return parts.toArray(new String[parts.size()]);
}
} |
package com.github.kory33.PluginUpdateNotificationAPI.github;
import java.util.List;
import com.github.kory33.PluginUpdateNotificationAPI.UpdateNotifyPlugin;
public abstract class GithubUpdateNotifyPlugin extends UpdateNotifyPlugin {
private final GithubVersionManager gVersionManager = new GithubVersionManager();
/**
* <p>
* This function is expected to return true if the plugin should follow <strong>only version releases.</strong>
* Version releases are the releases which are tagged with version, for instance, 1.0.2 or 0.5.3.2.
* <p>
* For the release to be considered as "new version", there should be increase in the version number,
* and the release must have a tag that matches the following regular expression: ($v?%d(\.%d)*)
*/
public abstract boolean followVersions();
@Override
public boolean checkForUpdate() {
List<GithubRelease> releases;
if(this.followVersions()){
releases = this.gVersionManager.getVersionReleases();
}else{
releases = this.gVersionManager.getReleases();
}
if(releases.iterator().hasNext()){
return true;
}
return false;
}
public GithubRelease getLatestRelease(){
if(!this.checkForUpdate()){
return null;
}
if(this.followVersions()){
return this.gVersionManager.getLatestVersionRelease();
}else{
return this.gVersionManager.getLatestRelease();
}
}
@Override
public String getUpdateLogString() {
GithubRelease latestRelease = this.getLatestRelease();
return "New version available! " + this.getPluginName() + latestRelease.getVersion() + "[" + latestRelease.getLink() + "]";
}
@Override
public String getUpdatePlayerLogString() {
GithubRelease latestRelease = this.getLatestRelease();
return "New version available! " + this.getPluginName() + latestRelease.getVersion() + "[" + latestRelease.getLink() + "]";
}
@Override
public String getUpToDateLogString() {
return this.getPluginName() + " is up-to-date.";
}
@Override
public String getUpToDatePlayerLogString() {
return this.getPluginName() + " is up-to-date.";
}
} |
package com.welovecoding.netbeans.plugin.editorconfig.processor;
import com.welovecoding.netbeans.plugin.editorconfig.io.exception.FileAccessException;
import com.welovecoding.netbeans.plugin.editorconfig.io.model.MappedCharset;
import com.welovecoding.netbeans.plugin.editorconfig.io.writer.StyledDocumentWriter;
import com.welovecoding.netbeans.plugin.editorconfig.mapper.EditorConfigPropertyMapper;
import com.welovecoding.netbeans.plugin.editorconfig.model.EditorConfigConstant;
import com.welovecoding.netbeans.plugin.editorconfig.model.MappedEditorConfig;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.FinalNewLineOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.IndentSizeOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.IndentStyleOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.LineEndingOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.TabWidthOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.TrimTrailingWhiteSpaceOperation;
import com.welovecoding.netbeans.plugin.editorconfig.processor.operation.tobedone.CharsetOperation;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.SwingUtilities;
import org.netbeans.api.project.Project;
import org.netbeans.modules.editor.indent.spi.CodeStylePreferences;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.text.NbDocument;
import org.openide.util.Lookup;
import org.openide.util.Utilities;
public class EditorConfigProcessor {
private static final Logger LOG = Logger.getLogger(EditorConfigProcessor.class.getSimpleName());
public static final Level OPERATION_LOG_LEVEL = Level.INFO;
private String filePath;
private final String projectPath;
public EditorConfigProcessor() {
// Project nbProject = OpenProjects.getDefault().getMainProject();
Lookup lookup = Utilities.actionsGlobalContext();
Project project = lookup.lookup(Project.class);
if (project == null) {
projectPath = "";
} else {
FileObject nbProjectDirectory = project.getProjectDirectory();
projectPath = nbProjectDirectory.getPath();
}
}
/**
* Applies properties defined in an ".editorconfig" file to a DataObject.
*
* If a supported property is found, then changes are made to a StringBuilder
* instance.
*
* The StringBuilder instance is passed as a reference to operations that can
* then perform their actions on this instance.
*
* After all operations were performed, the changes will be flushed.
*
* @param dataObject
*/
public void applyRulesToFile(DataObject dataObject) {
FileObject primaryFile = dataObject.getPrimaryFile();
filePath = primaryFile.getPath();
LOG.log(Level.INFO, "Apply rules to file: {0} (MIME type: {1})",
new Object[]{filePath, primaryFile.getMIMEType()});
// Check if the file's MIME type can be edited
// Allowed MIME types are: text/html, text/javascript, text/x-java, text/xml, ...
if (!primaryFile.getMIMEType().startsWith("text/")) {
LOG.log(Level.INFO, "Skipping file because it has an unsupported MIME type.");
return;
}
// Check if file is stored in a critical path
for (String directoryName : SmartSkip.IGNORED_FILES) {
// Note: Always use forward slashes here
String path = projectPath + "/" + directoryName;
if (filePath.startsWith(path)) {
LOG.log(Level.INFO, "Skipping file because it is located in an unsupported directory.", path);
return;
}
}
MappedEditorConfig config = readRulesForFile(filePath);
FileInfo info = excuteOperations(dataObject, config);
// Apply EditorConfig operations
if (info.isStyleFlushNeeded()) {
LOG.log(Level.INFO, "Flush style changes for: {0}", filePath);
flushStyles(info);
}
if (info.isFileChangeNeeded()) {
LOG.log(Level.INFO, "Flush file changes for: {0}", filePath);
flushFile(info);
}
}
protected FileInfo excuteOperations(DataObject dataObject, MappedEditorConfig config) {
LOG.log(Level.INFO, "Mapped rules for: {0}", filePath);
LOG.log(Level.INFO, config.toString());
FileInfo info = new FileInfo(dataObject);
boolean fileChangeNeeded = false;
boolean styleFlushNeeded = false;
FileObject primaryFile = dataObject.getPrimaryFile();
StringBuilder content;
try {
content = new StringBuilder(primaryFile.asText());
} catch (IOException ex) {
content = new StringBuilder();
}
info.setContent(content);
if (config.getEndOfLine() != null) {
info.setEndOfLine(config.getEndOfLine());
}
EditorCookie cookie = getEditorCookie(dataObject);
boolean isOpenedInEditor = (cookie != null) && (cookie.getDocument() != null);
info.setOpenedInEditor(isOpenedInEditor);
info.setCookie(cookie);
// 1. "charset"
MappedCharset mappedCharset = config.getCharset();
if (mappedCharset != null) {
logOperation(EditorConfigConstant.CHARSET, mappedCharset.getName());
boolean changedCharset = new CharsetOperation().run(dataObject, mappedCharset);
fileChangeNeeded = fileChangeNeeded || changedCharset;
info.setCharset(mappedCharset.getCharset());
} else {
info.setCharset(StandardCharsets.UTF_8);
}
// 2. "end_of_line"
if (config.getEndOfLine() != null) {
logOperation(EditorConfigConstant.END_OF_LINE, config.getEndOfLine());
boolean endOfLine = new LineEndingOperation().operate(info);
fileChangeNeeded = fileChangeNeeded || endOfLine;
}
// 3. "indent_size"
if (config.getIndentSize() == -2 || config.getIndentSize() > -1) {
logOperation(EditorConfigConstant.INDENT_SIZE, config.getIndentSize());
boolean changedIndentSize = new IndentSizeOperation(primaryFile).changeIndentSize(config.getIndentSize());
styleFlushNeeded = styleFlushNeeded || changedIndentSize;
}
// 4. "indent_style "
if (config.getIndentStyle() != null) {
logOperation(EditorConfigConstant.INDENT_STYLE, config.getIndentStyle());
boolean changedIndentStyle = new IndentStyleOperation(primaryFile).changeIndentStyle(config.getIndentStyle());
styleFlushNeeded = styleFlushNeeded || changedIndentStyle;
}
// 5. "insert_final_newline"
if (config.isInsertFinalNewLine()) {
logOperation(EditorConfigConstant.INSERT_FINAL_NEWLINE, config.isInsertFinalNewLine());
boolean changedLineEndings = new FinalNewLineOperation().operate(info);
fileChangeNeeded = fileChangeNeeded || changedLineEndings;
}
// 6. "tab_width"
if ((config.getTabWidth() > -1)
&& (config.getIndentStyle() != null)
&& (config.getIndentStyle().equals(EditorConfigConstant.INDENT_STYLE_TAB))) {
logOperation(EditorConfigConstant.TAB_WIDTH, config.getIndentStyle());
boolean changedTabWidth = new TabWidthOperation(primaryFile).changeTabWidth(config.getTabWidth());
fileChangeNeeded = fileChangeNeeded || changedTabWidth;
}
// 7. "trim_trailing_whitespace"
if (config.isTrimTrailingWhiteSpace()) {
logOperation(EditorConfigConstant.TRIM_TRAILING_WHITESPACE, config.isTrimTrailingWhiteSpace());
boolean trimmedWhiteSpaces = new TrimTrailingWhiteSpaceOperation().operate(info);
fileChangeNeeded = fileChangeNeeded || trimmedWhiteSpaces;
}
if (mappedCharset != null) {
} else {
info.setCharset(StandardCharsets.UTF_8);
}
info.setFileChangeNeeded(fileChangeNeeded);
info.setStyleFlushNeeded(styleFlushNeeded);
return info;
}
protected void flushFile(FileInfo info) {
if (info.isOpenedInEditor()) {
updateChangesInEditorWindow(info);
} else {
updateChangesInFile(info);
}
}
private void flushStyles(FileInfo info) {
try {
Preferences codeStyle = CodeStylePreferences.get(info.getFileObject(), info.getFileObject().getMIMEType()).getPreferences();
codeStyle.flush();
if (info.isOpenedInEditor()) {
updateChangesInEditorWindow(info);
}
} catch (BackingStoreException ex) {
LOG.log(Level.SEVERE, "Error flushing code styles: {0}", ex.getMessage());
}
}
private EditorCookie getEditorCookie(DataObject dataObject) {
return dataObject.getLookup().lookup(EditorCookie.class);
}
private void logOperation(String key, Object value) {
LOG.log(Level.INFO, "\"{0}\": {1} ({2})", new Object[]{
key,
value,
filePath
});
}
/**
* Takes the absolute path to a file which should be validated using the
* EditorConfig file.
*
* @param filePath Example: C:\project\awesome\index.html
* @return
*/
private MappedEditorConfig readRulesForFile(String filePath) {
return EditorConfigPropertyMapper.createEditorConfig(filePath);
}
private void updateChangesInEditorWindow(final FileInfo info) {
LOG.log(Level.INFO, "Update changes in Editor window for: {0}", info.getPath());
final EditorCookie cookie = info.getCookie();
Runnable runner = () -> {
NbDocument.runAtomic(cookie.getDocument(), () -> {
try {
StyledDocumentWriter.writeWithEditorKit(info);
} catch (FileAccessException ex) {
LOG.log(Level.SEVERE, ex.getMessage());
}
});
};
if (SwingUtilities.isEventDispatchThread()) {
runner.run();
} else {
SwingUtilities.invokeLater(runner);
}
}
/**
* TODO: Make sure that a Reformat is done to write correct indentions.
*
* @param info
*/
private void updateChangesInFile(FileInfo info) {
LOG.log(Level.INFO, "Write content (with all rules applied) to file: {0}",
info.getFileObject().getPath());
WriteStringToFileTask task = new WriteStringToFileTask(info);
task.run();
}
} |
package minhhai2209.jirapluginconverter.plugin.lifecycle;
import java.util.UUID;
import org.springframework.beans.factory.DisposableBean;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.event.PluginEventListener;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.events.PluginDisabledEvent;
import com.atlassian.plugin.event.events.PluginEnabledEvent;
import com.atlassian.plugin.event.events.PluginUninstalledEvent;
import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting;
import minhhai2209.jirapluginconverter.utils.ExceptionUtils;
public class PluginLifeCycleEventListener implements DisposableBean {
private EventType currentPluginStatus = null;
private boolean registered = false;
private String source = UUID.randomUUID().toString();
private boolean newlyInstalled = true;
private PluginLifeCycleEventHandler pluginLifeCycleEventHandler;
public PluginLifeCycleEventListener(PluginLifeCycleEventHandler pluginLifeCycleEventHandler) {
this.pluginLifeCycleEventHandler = pluginLifeCycleEventHandler;
register();
}
private void handle(EventType nextPluginStatus, Plugin plugin) {
if (currentPluginStatus == null && EventType.enabled.equals(nextPluginStatus)) {
fireNullToEnabledEvent(plugin);
}
if (plugin != null && PluginSetting.PLUGIN_KEY.equals(plugin.getKey())) {
log("current " + currentPluginStatus + " next " + nextPluginStatus + " " + newlyInstalled);
if (EventType.uninstalled.equals(currentPluginStatus)) {
unregister();
return;
} else if (EventType.disabled.equals(currentPluginStatus) && EventType.enabled.equals(nextPluginStatus)) {
if (newlyInstalled) {
setPluginStatus(EventType.enabled, plugin);
} else {
fireDisabledToEnabledEvent(plugin);
unregister();
return;
}
} else if (currentPluginStatus == null) {
if (EventType.enabled.equals(nextPluginStatus)) {
setPluginStatus(EventType.installed, plugin);
} else {
setPluginStatus(nextPluginStatus, plugin);
}
} else if (!currentPluginStatus.equals(nextPluginStatus)) {
setPluginStatus(nextPluginStatus, plugin);
}
if (EventType.uninstalled.equals(currentPluginStatus)) {
unregister();
}
}
}
private void log(String message) {
// System.out.println(source + " " + message);
}
private void fireNullToEnabledEvent(Plugin plugin) {
log("fire null to enabled");
PluginNullToEnabledEvent event = new PluginNullToEnabledEvent(plugin, source);
PluginEventManager pluginEventManager = getPluginEventManager();
pluginEventManager.broadcast(event);
}
private void fireDisabledToEnabledEvent(Plugin plugin) {
log("fire disabled to enabled");
PluginDisabledToEnabledEvent event = new PluginDisabledToEnabledEvent(plugin, source);
PluginEventManager pluginEventManager = getPluginEventManager();
pluginEventManager.broadcast(event);
}
private PluginEventManager getPluginEventManager() {
PluginEventManager pluginEventManager = ComponentAccessor.getComponent(PluginEventManager.class);
return pluginEventManager;
}
private void unregister() {
try {
if (registered) {
PluginEventManager pluginEventManager = getPluginEventManager();
pluginEventManager.unregister(this);
registered = false;
}
} catch (Exception e) {
log(e.getMessage());
}
}
private void register() {
try {
if (!registered) {
PluginEventManager pluginEventManager = getPluginEventManager();
pluginEventManager.register(this);
registered = true;
}
} catch (Exception e) {
}
}
private void setPluginStatus(EventType nextPluginStatus, Plugin plugin) {
log("status " + currentPluginStatus + " to " + nextPluginStatus);
try {
newlyInstalled = false;
currentPluginStatus = nextPluginStatus;
switch (currentPluginStatus) {
case installed:
pluginLifeCycleEventHandler.onInstalled(plugin);
break;
case uninstalled:
pluginLifeCycleEventHandler.onUninstalled();
break;
case enabled:
pluginLifeCycleEventHandler.onEnabled();
break;
case disabled:
pluginLifeCycleEventHandler.onDisabled();
break;
default:
throw new IllegalArgumentException();
}
} catch (Exception e) {
log(e.getMessage());
ExceptionUtils.throwUnchecked(e);
}
}
@PluginEventListener
public void onPluginDisabledToEnabled(PluginDisabledToEnabledEvent event) {
if (event == null) return;
log("pre receive disabled to enabled");
if (!source.equals(event.getSource())) {
log("receive disabled to enabled");
currentPluginStatus = EventType.disabled;
}
}
@PluginEventListener
public void onPluginNullToEnabled(PluginNullToEnabledEvent event) {
if (event == null) return;
log("pre receive null to enabled");
if (!source.equals(event.getSource())) {
log("receive null to enabled");
handle(EventType.enabled, event.getPlugin());
}
}
@PluginEventListener
public void onPluginEnabled(PluginEnabledEvent event) {
if (event == null) return;
handle(EventType.enabled, event.getPlugin());
}
@PluginEventListener
public void onPluginDisabled(PluginDisabledEvent event) {
if (event == null) return;
handle(EventType.disabled, event.getPlugin());
}
@PluginEventListener
public void onPluginUninstalledEvent(PluginUninstalledEvent event) {
if (event == null) return;
handle(EventType.uninstalled, event.getPlugin());
}
@Override
public void destroy() throws Exception {
handle(EventType.disabled, null);
}
} |
package net.sf.taverna.t2.activities.xpath.ui.servicedescription;
import javax.swing.Icon;
import net.sf.taverna.t2.activities.xpath.XPathActivity;
import net.sf.taverna.t2.activities.xpath.XPathActivityConfigurationBean;
import net.sf.taverna.t2.servicedescriptions.AbstractTemplateService;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
/**
*
* @author Sergejs Aleksejevs
*/
public class XPathTemplateService extends AbstractTemplateService<XPathActivityConfigurationBean>
{
public XPathTemplateService ()
{
super();
/*
// TODO - re-enable this if it is necessary to add another folder inside "Service templates" in the Service Panel
templateService = new AbstractTemplateService.TemplateServiceDescription() {
public List<String> getPath() {
return Arrays.asList(SERVICE_TEMPLATES, "XPath");
}
};
*/
}
@Override
public Class<XPathActivity> getActivityClass() {
return XPathActivity.class;
}
@Override
/**
* Default values for this template service are provided in this method.
*/
public XPathActivityConfigurationBean getActivityConfiguration()
{
return (XPathActivityConfigurationBean.getDefaultInstance());
}
@Override
public Icon getIcon() {
return XPathActivityIcon.getXPathActivityIcon();
}
public String getName() {
return "XPath Service";
}
public String getDescription() {
return "Service for point-and-click creation of XPath expressions for XML data";
}
@SuppressWarnings("unchecked")
public static ServiceDescription getServiceDescription() {
XPathTemplateService gts = new XPathTemplateService();
return gts.templateService;
}
public String getId() {
return "http:
}
} |
package org.mtransit.parser.ca_burlington_transit_bus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BurlingtonTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(@Nullable String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-burlington-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new BurlingtonTransitBusAgencyTools().start(args);
}
@Nullable
private HashSet<Integer> serviceIdInts;
@Override
public void start(@NotNull String[] args) {
MTLog.log("Generating Burlington Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIdInts = extractUsefulServiceIdInts(args, this, true);
super.start(args);
MTLog.log("Generating Burlington Transit bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIdInts != null && this.serviceIdInts.isEmpty();
}
@Override
public boolean excludeCalendar(@NotNull GCalendar gCalendar) {
if (this.serviceIdInts != null) {
return excludeUselessCalendarInt(gCalendar, this.serviceIdInts);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(@NotNull GCalendarDate gCalendarDates) {
if (this.serviceIdInts != null) {
return excludeUselessCalendarDateInt(gCalendarDates, this.serviceIdInts);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(@NotNull GTrip gTrip) {
if (this.serviceIdInts != null) {
return excludeUselessTripInt(gTrip, this.serviceIdInts);
}
return super.excludeTrip(gTrip);
}
@NotNull
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
private static final String A = "A";
private static final String B = "B";
private static final String X = "X";
private static final long RID_ENDS_WITH_A = 1000L;
private static final long RID_ENDS_WITH_B = 2000L;
private static final long RID_ENDS_WITH_X = 24000L;
@Override
public long getRouteId(@NotNull GRoute gRoute) {
String routeId = gRoute.getRouteShortName();
if (routeId.length() > 0 && Utils.isDigitsOnly(routeId)) {
return Integer.parseInt(routeId); // using stop code as stop ID
}
Matcher matcher = DIGITS.matcher(routeId);
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
if (routeId.endsWith(A)) {
return RID_ENDS_WITH_A + digits;
} else if (routeId.endsWith(B)) {
return RID_ENDS_WITH_B + digits;
} else if (routeId.endsWith(X)) {
return RID_ENDS_WITH_X + digits;
}
}
throw new MTLog.Fatal("Can't find route ID for %s!", gRoute);
}
@NotNull
@Override
public String cleanRouteLongName(@NotNull String routeLongName) {
routeLongName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, routeLongName, getIgnoredWords());
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR = "006184"; // BLUE
@NotNull
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public void setTripHeadsign(@NotNull MRoute mRoute, @NotNull MTrip mTrip, @NotNull GTrip gTrip, @NotNull GSpec gtfs) {
mTrip.setHeadsignString(
cleanTripHeadsign(gTrip.getTripHeadsignOrDefault()),
gTrip.getDirectionIdOrDefault()
);
}
@Override
public boolean directionFinderEnabled() {
return true;
}
@Override
public boolean mergeHeadsign(@NotNull MTrip mTrip, @NotNull MTrip mTripToMerge) {
throw new MTLog.Fatal("Unexpected trips to merge %s and %s.", mTrip, mTripToMerge);
}
@NotNull
@Override
public String cleanTripHeadsign(@NotNull String tripHeadsign) {
tripHeadsign = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, tripHeadsign, getIgnoredWords());
tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign);
tripHeadsign = CleanUtils.cleanBounds(tripHeadsign);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private String[] getIgnoredWords() {
return new String[]{"GO"};
}
@NotNull
@Override
public String cleanStopName(@NotNull String gStopName) {
gStopName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, gStopName, getIgnoredWords());
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(@NotNull GStop gStop) { // used for GTFS-RT
return super.getStopId(gStop);
}
} |
package org.helioviewer.plugins.eveplugin.radio.gui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import org.helioviewer.jhv.gui.filters.lut.LUT;
import org.helioviewer.plugins.eveplugin.radio.model.ColorLookupModel;
public class RadioOptionsPanel extends JPanel implements ActionListener {
private JComboBox lut;
private final Map<String, LUT> lutMap;
public RadioOptionsPanel() {
super();
lutMap = LUT.getStandardList();
initVisualComponents();
}
private void initVisualComponents() {
setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
lut = new JComboBox(lutMap.keySet().toArray());
lut.setSelectedItem("Rainbow 2");
lut.addActionListener(this);
add(lut);
}
@Override
public void actionPerformed(ActionEvent e) {
ColorLookupModel.getInstance().setLUT(LUT.getStandardList().get((lut.getSelectedItem())));
}
/**
* Adds a color table to the available list and set it active
*
* @param lut
* Color table to add
*/
public void addLut(LUT newLut) {
if (lutMap.put(newLut.getName(), newLut) == null) {
lut.addItem(newLut.getName());
}
lut.setSelectedItem(newLut.getName());
ColorLookupModel.getInstance().setLUT(newLut);
}
} |
package ca.corefacility.bioinformatics.irida.config.workflow;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.google.common.collect.Sets;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowException;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowLoadException;
import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.Analysis;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.TestAnalysis;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.type.AnalysisType;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.type.config.AnalysisTypeSet;
import ca.corefacility.bioinformatics.irida.model.workflow.config.IridaWorkflowIdSet;
import ca.corefacility.bioinformatics.irida.model.workflow.config.IridaWorkflowSet;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowLoaderService;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService;
/**
* Class used to load up test workflows.
*
*
*/
@Configuration
@Profile("test")
public class IridaWorkflowsTestConfig {
@Autowired
private IridaWorkflowLoaderService iridaWorkflowLoaderService;
private UUID testAnalysisDefaultId = UUID.fromString("739f29ea-ae82-48b9-8914-3d2931405db6");
private UUID phylogenomicsPipelineDefaultId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8");
private UUID assemblyAnnotationPipelineDefaultId = UUID.fromString("8c438951-484a-48da-be2b-93b7d29aa2a3");
@Bean
public IridaWorkflowSet iridaWorkflows() throws IOException, IridaWorkflowLoadException, URISyntaxException {
Path testAnalysisPath = Paths.get(TestAnalysis.class.getResource("workflows/TestAnalysis").toURI());
Path phylogenomicsAnalysisPath = Paths
.get(Analysis.class.getResource("workflows/AnalysisPhylogenomicsPipeline").toURI());
Path assemblyAnnotationPath = Paths
.get(Analysis.class.getResource("workflows/AnalysisAssemblyAnnotation").toURI());
Set<IridaWorkflow> workflowsSet = iridaWorkflowLoaderService.loadAllWorkflowImplementations(testAnalysisPath);
workflowsSet.addAll(iridaWorkflowLoaderService.loadAllWorkflowImplementations(phylogenomicsAnalysisPath));
workflowsSet.addAll(iridaWorkflowLoaderService.loadAllWorkflowImplementations(assemblyAnnotationPath));
return new IridaWorkflowSet(workflowsSet);
}
@Bean
public IridaWorkflowIdSet defaultIridaWorkflows() {
return new IridaWorkflowIdSet(Sets.newHashSet(testAnalysisDefaultId, phylogenomicsPipelineDefaultId, assemblyAnnotationPipelineDefaultId));
}
@Bean
public AnalysisTypeSet disabledAnalysisTypes() {
return new AnalysisTypeSet();
}
@Bean
public IridaWorkflowsService iridaWorkflowsService(IridaWorkflowSet iridaWorkflows,
IridaWorkflowIdSet defaultIridaWorkflows, AnalysisTypeSet disabledAnalysisTypes)
throws IridaWorkflowException {
return new IridaWorkflowsService(iridaWorkflows, defaultIridaWorkflows, disabledAnalysisTypes,
IridaWorkflowsConfig.UNKNOWN_WORKFLOW);
}
} |
package net.finmath.marketdata.model.curves.locallinearregression;
import java.time.LocalDate;
import org.apache.commons.math3.distribution.AbstractRealDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.jblas.DoubleMatrix;
import org.junit.Assert;
import org.junit.Test;
import net.finmath.marketdata.model.curves.CurveInterface;
public class CurveEstimationTest {
/**
* Simple test of curve consisting of two points..
*/
// @Test
// public void testLinearInterpolation() {
// LocalDate date=LocalDate.now();
// double[] X = { 0.0 , 1.0 };
// double[] Y = { 1.0 , 0.8 };
// double bandwidth = 1500;
// CurveEstimation estimatedcurve = new CurveEstimation(date, bandwidth, X, Y, X, 0.5);
// CurveInterface regressionCurve = estimatedcurve.getRegressionCurve();
// Assert.assertEquals("left extrapolatoin", 1.0, regressionCurve.getValue(-0.5), 1E-12);
// Assert.assertEquals("left interpolation", 0.95, regressionCurve.getValue(0.25), 1E-12);
// Assert.assertEquals("center interpolation", 0.9, regressionCurve.getValue(0.50), 1E-12);
// Assert.assertEquals("right interpolation", 0.85, regressionCurve.getValue(0.75), 1E-12);
// Assert.assertEquals("right extrapolatoin", 0.8, regressionCurve.getValue(1.5), 1E-12);
// AbstractRealDistribution kernel=new NormalDistribution();
// double K=kernel.density(0.0);
// DoubleMatrix R=new DoubleMatrix(new double[] {K*(Y[0]+Y[1]),Y[1]*(X[1]-X[0])*K} );
// DoubleMatrix M=new DoubleMatrix(new double[][] {{2*K,K*(X[1]-X[0])},{K*(X[1]-X[0]),K*(X[1]-X[0])*(X[1]-X[0])}} );
// double detM= M.get(0,0)*M.get(1, 1)-M.get(1,0)*M.get(1,0);
// DoubleMatrix MInv=new DoubleMatrix(new double[][] {{M.get(1, 1),-M.get(1,0)},{-M.get(1,0),M.get(0,0)}} );
// MInv=MInv.mul(1/detM);
// DoubleMatrix a=MInv.mmul(R);
// System.out.println(R.toString());
// System.out.println(M.toString());
// System.out.println(a.toString());
/**
* Regression matrix (currently no test, just for inspection)
*/
// @Test
// public void testRegressionMatrix() {
// double[] X = { 0.0 , 1.0 };
// double[] Y = { 1.0 , 0.8 };
// AbstractRealDistribution kernel=new NormalDistribution();
// double K=kernel.density(0.0);
// DoubleMatrix R=new DoubleMatrix(new double[] {K*(Y[0]+Y[1]),Y[1]*(X[1]-X[0])*K} );
// DoubleMatrix M=new DoubleMatrix(new double[][] {{2*K,K*(X[1]-X[0])},{K*(X[1]-X[0]),K*(X[1]-X[0])*(X[1]-X[0])}} );
// double detM= M.get(0,0)*M.get(1, 1)-M.get(1,0)*M.get(1,0);
// DoubleMatrix MInv=new DoubleMatrix(new double[][] {{M.get(1, 1),-M.get(1,0)},{-M.get(1,0),M.get(0,0)}} );
// MInv=MInv.mul(1/detM);
// DoubleMatrix a=MInv.mmul(R);
// System.out.println(R.toString());
// System.out.println(M.toString());
// System.out.println(a.toString());
} |
import javax.swing.JPanel;
import java.awt.Dimension;
import javax.swing.border.BevelBorder;
import javax.swing.BorderFactory;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileInputStream;
import java.io.File;
import java.nio.file.Files;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import javax.swing.JPasswordField;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.dom.DOMSource;
import javax.swing.JOptionPane;
public class DBConfig extends JPanel{
Document doc=null;
File theone;
JTextField tdatabase,tserver,tuser;
JPasswordField tpassword;
public DBConfig(){
setLayout(null);
setPreferredSize(new Dimension(450,480));
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
setBackground(Color.WHITE);
JLabel file = new JLabel("File: ");
file.setBounds(15,10,50,20);
add(file);
final JTextField tfile = new JTextField();
tfile.setBounds(80,10,170,25);
add(tfile);
JButton browse = new JButton("Browse");
browse.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new XMLFilter());
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select XML File");
if (chooser.showOpenDialog(Repository.frame) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
try{tfile.setText(f.getCanonicalPath());}
catch(Exception e){e.printStackTrace();}}}});
browse.setBounds(255,13,90,20);
add(browse);
JButton upload = new JButton("Upload");
upload.setBounds(355,10,90,20);
upload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
try{File f = new File(tfile.getText());
Repository.c.cd(Repository.REMOTEDATABASECONFIGPATH);
FileInputStream stream = new FileInputStream(f);
Repository.c.put(stream,f.getName());
stream.close();
Files.copy(f.toPath(), new File(Repository.getConfigDirectory()+
Repository.getBar()+f.getName()).toPath(), REPLACE_EXISTING);
Repository.resetDBConf(f.getName(),false);}
catch(Exception e){e.printStackTrace();}}});
add(upload);
JLabel database = new JLabel("Database: ");
database.setBounds(15,55,65,20);
add(database);
tdatabase = new JTextField();
tdatabase.setBounds(80,55,170,25);
add(tdatabase);
JLabel server = new JLabel("Server: ");
server.setBounds(15,80,50,20);
add(server);
tserver = new JTextField();
tserver.setBounds(80,80,170,25);
add(tserver);
JLabel user = new JLabel("User: ");
user.setBounds(15,105,50,20);
add(user);
tuser = new JTextField();
tuser.setBounds(80,105,170,25);
add(tuser);
JLabel password = new JLabel("Password: ");
password.setBounds(15,130,70,20);
add(password);
tpassword = new JPasswordField();
tpassword.setBounds(80,130,170,25);
add(tpassword);
refresh();
JButton save = new JButton("Save");
save.setBounds(180,155,70,20);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
if(doc!=null){
if(tpassword.getPassword().length == 0){JOptionPane.showMessageDialog(
DBConfig.this, "Warning, password not set", "Warning", JOptionPane.WARNING_MESSAGE);}
theone = new File(Repository.temp+Repository.getBar()+"Twister"+
Repository.getBar()+"config"+Repository.getBar()+new File(
Repository.REMOTEDATABASECONFIGFILE).getName());
try{NodeList nodeLst = doc.getElementsByTagName("server");
if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.
item(0).getChildNodes().item(0).setNodeValue(tserver.getText());
else nodeLst.item(0).appendChild(doc.createTextNode(
tserver.getText()));
nodeLst = doc.getElementsByTagName("database");
if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.
item(0).getChildNodes().item(0).setNodeValue(tdatabase.
getText());
else nodeLst.item(0).appendChild(doc.createTextNode(tdatabase.
getText()));
nodeLst = doc.getElementsByTagName("user");
if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.
item(0).getChildNodes().item(0).setNodeValue(tuser.getText());
else nodeLst.item(0).appendChild(doc.createTextNode(tuser.
getText()));
if(tpassword.getPassword().length != 0 && !(new String(
tpassword.getPassword()).equals("****"))){
nodeLst = doc.getElementsByTagName("password");
if(nodeLst.item(0).getChildNodes().getLength()>0)nodeLst.
item(0).getChildNodes().item(0).setNodeValue(new String(
tpassword.getPassword()));
else nodeLst.item(0).appendChild(doc.createTextNode(
new String(tpassword.getPassword())));}}
catch(Exception e){System.out.println(doc.getDocumentURI()+
" may not be properly formatted");}
Result result = new StreamResult(theone);
try{DOMSource source = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.
newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
try{Repository.c.cd(Repository.REMOTEDATABASECONFIGPATH);}
catch(Exception e){System.out.println("could not get "+
Repository.REMOTEDATABASECONFIGPATH);
e.printStackTrace();}
FileInputStream input = new FileInputStream(theone);
Repository.c.put(input, theone.getName());
input.close();}
catch(Exception e){e.printStackTrace();
System.out.println("Could not save in file : "+Repository.
temp+Repository.getBar()+"Twister"+Repository.getBar()+"Config"+
Repository.getBar()+Repository.REMOTEDATABASECONFIGFILE+" and send to "+
Repository.REMOTEDATABASECONFIGPATH);}}}});
add(save);}
public void refresh(){
try{
InputStream in = null;
try{Repository.c.cd(Repository.REMOTEDATABASECONFIGPATH);
System.out.println("changed to:"+ Repository.REMOTEDATABASECONFIGPATH);
in = Repository.c.get(Repository.REMOTEDATABASECONFIGFILE);}
catch(Exception e){e.printStackTrace();
System.out.println("Could not get: "+Repository.REMOTEDATABASECONFIGFILE);}
byte [] data = new byte[100];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
theone = new File(Repository.temp+Repository.getBar()+"Twister"+Repository.
getBar()+"Config"+Repository.getBar()+new File(Repository.REMOTEDATABASECONFIGFILE).getName());
try{while ((nRead = in.read(data, 0, data.length)) != -1){buffer.write(data, 0, nRead);}
buffer.flush();
FileOutputStream out = new FileOutputStream(theone);
buffer.writeTo(out);
out.close();
buffer.close();
in.close();}
catch(Exception e){e.printStackTrace();
System.out.println("Could not write "+Repository.REMOTEDATABASECONFIGFILE+" on local hdd");}
try{DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(theone);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("server");
tserver.setText(nodeLst.item(0).getChildNodes().item(0).getNodeValue());
nodeLst = doc.getElementsByTagName("database");
tdatabase.setText(nodeLst.item(0).getChildNodes().item(0).getNodeValue());
nodeLst = doc.getElementsByTagName("password");
tpassword.setText(nodeLst.item(0).getChildNodes().item(0).getNodeValue());
if(!tpassword.getPassword().equals(""))tpassword.setText("****");
nodeLst = doc.getElementsByTagName("user");
tuser.setText(nodeLst.item(0).getChildNodes().item(0).getNodeValue());}
catch(Exception e){System.out.println(Repository.temp+Repository.getBar()+
"Twister"+Repository.getBar()+"Config"+Repository.getBar()+new File(Repository.
REMOTEDATABASECONFIGFILE).getName()+" is corrupted or incomplete");}}
catch(Exception e){
e.printStackTrace();
System.out.println("Could not refresh dbconfig structure");}}} |
package tech.vision8.embjetty.app.run;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
/**
* @author vision8
*/
public class EmbJettyAppStart {
private static final Logger log = LoggerFactory.getLogger(EmbJettyAppStart.class);
public static Instant startTime = Instant.now();
public static void main(String... args) {
log.info("
log.info("- Starting up -");
log.info("
try {
WebAppServer.instance().start();
} catch (Exception e) {
log.error("Webapp server startup failed: " + e.getMessage());
}
}
} |
package com.sinewang.statemate.core.spi;
import one.kii.statemate.core.spi.CreateIntensionSpi;
import one.kii.summer.io.exception.*;
import one.kii.summer.io.sender.ErestPost;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.ArrayList;
import java.util.List;
@ConfigurationProperties(prefix = "metamate")
@Component
public class DefaultCreateIntensionSpi implements CreateIntensionSpi {
private static String TREE = "master";
private static String VISIBILITY_PUBLIC = "public";
private static String URI = "/{ownerId}/intension";
private String baseUrl;
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
public String createPublicPrimitiveIntension(PrimitiveIntensionForm form) throws Panic {
String url = baseUrl + URI;
ErestPost erest = new ErestPost(form.getOwnerId());
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.set("extId", form.getExtId());
map.set("field", form.getField());
map.set("single", String.valueOf(form.isSingle()));
map.set("structure", form.getStructure());
map.set("visibility", VISIBILITY_PUBLIC);
IntensionReceipt receipt = null;
try {
receipt = erest.execute(url, map, IntensionReceipt.class, form.getOwnerId());
return receipt.getId();
} catch (Conflict conflict) {
return conflict.getKeys()[0];
} catch (BadRequest | NotFound | Forbidden | Panic panic) {
throw new Panic();
}
}
@Override
public String createPublicImportIntension(ImportIntensionForm form) throws Panic {
String url = baseUrl + URI;
ErestPost erest = new ErestPost(form.getOwnerId());
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.set("extId", form.getExtId());
map.set("field", form.getField());
map.set("single", String.valueOf(form.isSingle()));
map.set("structure", form.getStructure());
map.set("refExtId", form.getRefExtId());
map.set("visibility", VISIBILITY_PUBLIC);
try {
IntensionReceipt receipt = erest.execute(url, map, IntensionReceipt.class, form.getOwnerId());
return receipt.getExtId();
} catch (Conflict conflict) {
return conflict.getKeys()[0];
} catch (BadRequest | NotFound | Forbidden | Panic panic) {
throw new Panic();
}
}
private List<String> toList(String string) {
List<String> list = new ArrayList<>();
list.add(string);
return list;
}
} |
package com.exedio.cope;
import com.exedio.cope.testmodel.AttributeItem;
public class AttributeStringTest extends AttributeTest
{
public void testSomeString() throws ConstraintViolationException
{
assertEquals(item.TYPE, item.someString.getType());
assertEquals(item.TYPE, item.someStringUpperCase.getType());
assertEquals("someString", item.someString.getName());
assertEquals("someStringUpperCase", item.someStringUpperCase.getName());
{
final StringAttribute orig = Item.stringAttribute(Item.DEFAULT);
assertEquals(false, orig.isReadOnly());
assertEquals(false, orig.isNotNull());
assertEquals(false, orig.isLengthConstrained());
assertEquals(0, orig.getMinimumLength());
assertEquals(Integer.MAX_VALUE, orig.getMaximumLength());
final StringAttribute copy = (StringAttribute)orig.copyAsTemplate();
assertEquals(false, copy.isReadOnly());
assertEquals(false, copy.isNotNull());
assertEquals(false, copy.isLengthConstrained());
assertEquals(0, copy.getMinimumLength());
assertEquals(Integer.MAX_VALUE, copy.getMaximumLength());
}
{
final StringAttribute orig = Item.stringAttribute(Item.READ_ONLY, 10);
assertEquals(true, orig.isReadOnly());
assertEquals(false, orig.isNotNull());
assertEquals(true, orig.isLengthConstrained());
assertEquals(10, orig.getMinimumLength());
assertEquals(Integer.MAX_VALUE, orig.getMaximumLength());
final StringAttribute copy = (StringAttribute)orig.copyAsTemplate();
assertEquals(true, copy.isReadOnly());
assertEquals(false, copy.isNotNull());
assertEquals(true, copy.isLengthConstrained());
assertEquals(10, copy.getMinimumLength());
assertEquals(Integer.MAX_VALUE, copy.getMaximumLength());
}
{
final StringAttribute orig = Item.stringAttribute(Item.NOT_NULL, 10, 20);
assertEquals(false, orig.isReadOnly());
assertEquals(true, orig.isNotNull());
assertEquals(true, orig.isLengthConstrained());
assertEquals(10, orig.getMinimumLength());
assertEquals(20, orig.getMaximumLength());
final StringAttribute copy = (StringAttribute)orig.copyAsTemplate();
assertEquals(false, copy.isReadOnly());
assertEquals(true, copy.isNotNull());
assertEquals(true, copy.isLengthConstrained());
assertEquals(10, copy.getMinimumLength());
assertEquals(20, copy.getMaximumLength());
}
assertEquals(null, item.getSomeString());
assertEquals(null, item.getSomeStringUpperCase());
assertEquals(null, item.getSomeStringLength());
item.setSomeString("someString");
assertEquals("someString", item.getSomeString());
assertEquals("SOMESTRING", item.getSomeStringUpperCase());
assertEquals(new Integer("someString".length()), item.getSomeStringLength());
assertContains(item, item.TYPE.search(item.someString.equal("someString")));
assertContains(item2, item.TYPE.search(item.someString.notEqual("someString")));
assertContains(item.TYPE.search(item.someString.equal("SOMESTRING")));
assertContains(item, item.TYPE.search(item.someNotNullString.like("someString")));
assertContains(item, item2, item.TYPE.search(item.someNotNullString.like("someString%")));
assertContains(item2, item.TYPE.search(item.someNotNullString.like("someString2%")));
assertContains(item, item.TYPE.search(item.someStringUpperCase.equal("SOMESTRING")));
assertContains(item, item.TYPE.search(item.someString.uppercase().equal("SOMESTRING")));
assertContains(item2, item.TYPE.search(item.someStringUpperCase.notEqual("SOMESTRING")));
assertContains(item2, item.TYPE.search(item.someString.uppercase().notEqual("SOMESTRING")));
assertContains(item.TYPE.search(item.someStringUpperCase.equal("someString")));
assertContains(item.TYPE.search(item.someString.uppercase().equal("someString")));
assertContains(item, item.TYPE.search(item.someStringLength.equal("someString".length())));
assertContains(item2, item.TYPE.search(item.someStringLength.notEqual("someString".length())));
assertContains(item.TYPE.search(item.someStringLength.equal("someString".length()+1)));
assertContains("someString", null, search(item.someString));
assertContains("someString", search(item.someString, item.someString.equal("someString")));
// TODO allow functions for select
//assertContains("SOMESTRING", search(item.someStringUpperCase, item.someString.equal("someString")));
item.passivateCopeItem();
assertEquals("someString", item.getSomeString());
assertEquals("SOMESTRING", item.getSomeStringUpperCase());
assertEquals(new Integer("someString".length()), item.getSomeStringLength());
item.setSomeString(null);
assertEquals(null, item.getSomeString());
assertEquals(null, item.getSomeStringUpperCase());
assertEquals(null, item.getSomeStringLength());
try
{
item.set(item.someString, new Integer(10));
fail();
}
catch(ClassCastException e)
{
assertEquals("expected string, got " + Integer.class.getName() + " for someString", e.getMessage());
}
}
public void testSomeNotNullString()
throws NotNullViolationException
{
assertEquals(item.TYPE, item.someNotNullString.getType());
assertEquals("someString", item.getSomeNotNullString());
item.setSomeNotNullString("someOtherString");
assertEquals("someOtherString", item.getSomeNotNullString());
try
{
item.setSomeNotNullString(null);
fail("should have thrown NotNullViolationException");
}
catch (NotNullViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.someNotNullString, e.getNotNullAttribute());
}
try
{
new AttributeItem(null, 5, 6l, 2.2, true, someItem, AttributeItem.SomeEnum.enumValue1);
fail("should have thrown NotNullViolationException");
}
catch(NotNullViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.someNotNullString, e.getNotNullAttribute());
}
}
} |
package stroom.security.impl;
import stroom.event.logging.rs.api.AutoLogged;
import stroom.event.logging.rs.api.AutoLogged.OperationType;
import stroom.security.api.UserIdentity;
import stroom.security.impl.session.SessionListResponse;
import stroom.security.impl.session.SessionListService;
import stroom.security.impl.session.UserIdentitySessionUtil;
import stroom.security.openid.api.OpenId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@AutoLogged(OperationType.MANUALLY_LOGGED)
public class SessionResourceImpl implements SessionResource {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionResourceImpl.class);
private final Provider<AuthenticationEventLog> eventLog;
private final Provider<SessionListService> sessionListService;
private final Provider<OpenIdManager> openIdManager;
@Inject
public SessionResourceImpl(final Provider<AuthenticationEventLog> eventLog,
final Provider<SessionListService> sessionListService,
final Provider<OpenIdManager> openIdManager) {
this.eventLog = eventLog;
this.sessionListService = sessionListService;
this.openIdManager = openIdManager;
}
@Override
public SessionLoginResponse login(final HttpServletRequest request, final String referrer) {
String redirectUri = null;
try {
LOGGER.info("Logging in session for '{}'", referrer);
final Optional<UserIdentity> userIdentity = openIdManager.get().loginWithRequestToken(request);
if (userIdentity.isEmpty()) {
// If the session doesn't have a user ref then attempt login.
final Map<String, String> paramMap = UrlUtils.createParamMap(referrer);
final String code = paramMap.get(OpenId.CODE);
final String stateId = paramMap.get(OpenId.STATE);
final String postAuthRedirectUri = OpenId.removeReservedParams(referrer);
redirectUri = openIdManager.get().redirect(request, code, stateId, postAuthRedirectUri);
}
if (redirectUri == null) {
redirectUri = OpenId.removeReservedParams(referrer);
}
return new SessionLoginResponse(userIdentity.isPresent(), redirectUri);
} catch (final RuntimeException e) {
LOGGER.error(e.getMessage(), e);
throw e;
}
}
@Override
public Boolean logout(final String authSessionId) {
LOGGER.info("Logging out session {}", authSessionId);
// TODO : We need to lookup the auth session in our user sessions
final HttpSession session = SessionMap.getSession(authSessionId);
final Optional<UserIdentity> userIdentity = UserIdentitySessionUtil.get(session);
if (session != null) {
// Invalidate the current user session
session.invalidate();
}
userIdentity.ifPresent(ui -> {
// Create an event for logout
eventLog.get().logoff(ui.getId());
});
return Boolean.TRUE;
}
@Override
@AutoLogged(OperationType.VIEW)
public SessionListResponse list(final String nodeName) {
LOGGER.debug("list({}) called", nodeName);
if (nodeName != null) {
return sessionListService.get().listSessions(nodeName);
} else {
return sessionListService.get().listSessions();
}
}
} |
package stsc.general.statistic.cost.function;
import java.text.ParseException;
import stsc.common.Settings;
import stsc.general.statistic.Statistics;
import stsc.general.testhelper.TestStatisticsHelper;
import junit.framework.TestCase;
public class CostWeightedSumFunctionTest extends TestCase {
public void testCostWeightedSumFunction() throws ParseException {
final Statistics statistics = TestStatisticsHelper.getStatistics();
final CostWeightedSumFunction function = new CostWeightedSumFunction();
final Double result = function.calculate(statistics);
assertEquals(-0.242883, result, Settings.doubleEpsilon);
function.addParameter("getPeriod", 0.5);
final Double result2 = function.calculate(statistics);
assertEquals(0.757116, result2, Settings.doubleEpsilon);
function.addParameter("getKelly", 0.3);
final Double result3 = function.calculate(statistics);
assertEquals(0.757116, result3, Settings.doubleEpsilon);
function.addParameter("getMaxLoss", 0.7);
final Double result4 = function.calculate(statistics);
assertEquals(127.457116, result4, Settings.doubleEpsilon);
}
} |
package com.example.reader.popups;
import com.example.reader.R;
import com.example.reader.ReaderActivity.ReaderMode;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.RadioButton;
public class ModeActivity extends Activity {
public static float posX, posY;
public static int imageHeight;
public static RadioButton listen, guidance;
static final int PICK_READER_MODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_activity_mode);
Bundle bundle = getIntent().getExtras();
posX = bundle.getFloat("posX", -1);
posY = bundle.getFloat("posY", -1);
imageHeight = bundle.getInt("imageHeight", -1);
listen = (RadioButton) findViewById(R.id.rdbtn_mode_listen);
guidance = (RadioButton) findViewById(R.id.rdbtn_mode_highlight);
ReaderMode mode = (ReaderMode) bundle.get("readerMode");
switch (mode.getValue()) {
case 0:
listen.setChecked(true);
break;
case 1:
guidance.setChecked(true);
break;
default:
break;
}
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
View v = getWindow().getDecorView();
WindowManager.LayoutParams wmlp = (WindowManager.LayoutParams) v.getLayoutParams();
wmlp.gravity = Gravity.LEFT | Gravity.TOP;
wmlp.x = (int)posX;
wmlp.y = (int)posY;
getWindowManager().updateViewLayout(v, wmlp);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
public void onRadioButtonClicked(View view) {
Intent intent=new Intent();
intent.putExtra("chosenMode", -1);
switch(view.getId()) {
case R.id.rdbtn_mode_listen:
intent.putExtra("chosenMode", 0);
break;
case R.id.rdbtn_mode_highlight:
intent.putExtra("chosenMode", 1);
break;
}
setResult(RESULT_OK, intent);
finish();
}
} |
// Kyle Russell
// AUT University 2015
package com.graphi.display.layout;
import com.graphi.app.Consts;
import com.graphi.error.ErrorManager;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
public class AppResources
{
protected static AppResources instance;
protected Map<String, BufferedImage> resourceMap;
protected AppResources()
{
initResources();
}
protected void initResources()
{
try
{
resourceMap = new HashMap<>();
resourceMap.put("addIcon", ImageIO.read(new File(Consts.IMG_DIR + "addSmallIcon.png")));
resourceMap.put("removeIcon", ImageIO.read(new File(Consts.IMG_DIR + "removeSmallIcon.png")));
resourceMap.put("colourIcon", ImageIO.read(new File(Consts.IMG_DIR + "color_icon.png")));
resourceMap.put("clipIcon", ImageIO.read(new File(Consts.IMG_DIR + "clipboard.png")));
resourceMap.put("saveIcon", ImageIO.read(new File(Consts.IMG_DIR + "new_file.png")));
resourceMap.put("openIcon", ImageIO.read(new File(Consts.IMG_DIR + "open_icon.png")));
resourceMap.put("editBlackIcon", ImageIO.read(new File(Consts.IMG_DIR + "editblack.png")));
resourceMap.put("pointerIcon", ImageIO.read(new File(Consts.IMG_DIR + "pointer.png")));
resourceMap.put("moveIcon", ImageIO.read(new File(Consts.IMG_DIR + "move.png")));
resourceMap.put("moveSelectedIcon", ImageIO.read(new File(Consts.IMG_DIR + "move_selected.png")));
resourceMap.put("editSelectedIcon", ImageIO.read(new File(Consts.IMG_DIR + "editblack_selected.png")));
resourceMap.put("pointerSelectedIcon", ImageIO.read(new File(Consts.IMG_DIR + "pointer_selected.png")));
resourceMap.put("graphIcon", ImageIO.read(new File(Consts.IMG_DIR + "graph.png")));
resourceMap.put("tableIcon", ImageIO.read(new File(Consts.IMG_DIR + "table.png")));
resourceMap.put("executeIcon", ImageIO.read(new File(Consts.IMG_DIR + "execute.png")));
resourceMap.put("resetIcon", ImageIO.read(new File(Consts.IMG_DIR + "reset.png")));
resourceMap.put("editIcon", ImageIO.read(new File(Consts.IMG_DIR + "edit.png")));
resourceMap.put("playIcon", ImageIO.read(new File(Consts.IMG_DIR + "play.png")));
resourceMap.put("stopIcon", ImageIO.read(new File(Consts.IMG_DIR + "stop.png")));
resourceMap.put("recordIcon", ImageIO.read(new File(Consts.IMG_DIR + "record.png")));
resourceMap.put("closeIcon", ImageIO.read(new File(Consts.IMG_DIR + "close.png")));
}
catch(IOException e)
{
ErrorManager.GUIErrorMessage("Failed to load resources", true, e, null);
}
}
public Map<String, BufferedImage> getResourceMap()
{
return resourceMap;
}
public BufferedImage getResource(String resourceName)
{
return resourceMap.get(resourceName);
}
public boolean hasResource(String resourceName)
{
return resourceMap.containsKey(resourceName);
}
public static AppResources getResources()
{
if(instance == null) instance = new AppResources();
return instance;
}
} |
package com.irccloud.android;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
public class BuffersDataSource {
public class Buffer {
int bid;
int cid;
long min_eid;
long last_seen_eid;
String name;
String type;
int archived;
int deferred;
String away_msg;
}
public class comparator implements Comparator<Buffer> {
public int compare(Buffer b1, Buffer b2) {
int joined1 = 1, joined2 = 1;
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b1.bid);
if(c == null)
joined1 = 0;
c = ChannelsDataSource.getInstance().getChannelForBuffer(b2.bid);
if(c == null)
joined2 = 0;
if(b1.type.equals("conversation") && b2.type.equals("channel"))
return 1;
else if(b1.type.equals("channel") && b2.type.equals("conversation"))
return -1;
else if(joined1 != joined2)
return joined2 - joined1;
else
return b1.name.compareToIgnoreCase(b2.name);
}
}
private ArrayList<Buffer> buffers;
private static BuffersDataSource instance = null;
public static BuffersDataSource getInstance() {
if(instance == null)
instance = new BuffersDataSource();
return instance;
}
public BuffersDataSource() {
buffers = new ArrayList<Buffer>();
}
public void clear() {
buffers.clear();
}
public synchronized Buffer createBuffer(int bid, int cid, long min_eid, long last_seen_eid, String name, String type, int archived, int deferred) {
Buffer b = new Buffer();
b.bid = bid;
b.cid = cid;
b.min_eid = min_eid;
b.last_seen_eid = last_seen_eid;
b.name = name;
b.type = type;
b.archived = archived;
b.deferred = deferred;
buffers.add(b);
return b;
}
public synchronized void updateLastSeenEid(int bid, long last_seen_eid) {
Buffer b = getBuffer(bid);
if(b != null)
b.last_seen_eid = last_seen_eid;
}
public synchronized void updateArchived(int bid, int archived) {
Buffer b = getBuffer(bid);
if(b != null)
b.archived = archived;
}
public synchronized void updateName(int bid, String name) {
Buffer b = getBuffer(bid);
if(b != null)
b.name = name;
}
public synchronized void updateAway(int bid, String away_msg) {
Buffer b = getBuffer(bid);
if(b != null) {
b.away_msg = away_msg;
}
}
public synchronized void deleteBuffer(int bid) {
Buffer b = getBuffer(bid);
if(b != null)
buffers.remove(b);
}
public synchronized void deleteAllDataForBuffer(int bid) {
Buffer b = getBuffer(bid);
if(b != null) {
if(b.type.equalsIgnoreCase("channel")) {
ChannelsDataSource.getInstance().deleteChannel(bid);
UsersDataSource.getInstance().deleteUsersForChannel(b.cid, b.name);
}
EventsDataSource.getInstance().deleteEventsForBuffer(bid);
}
buffers.remove(b);
}
public synchronized Buffer getBuffer(int bid) {
Iterator<Buffer> i = buffers.iterator();
while(i.hasNext()) {
Buffer b = i.next();
if(b.bid == bid)
return b;
}
return null;
}
public synchronized Buffer getBufferByName(int cid, String name) {
Iterator<Buffer> i = buffers.iterator();
while(i.hasNext()) {
Buffer b = i.next();
if(b.name.equalsIgnoreCase(name))
return b;
}
return null;
}
public synchronized ArrayList<Buffer> getBuffersForServer(int cid) {
ArrayList<Buffer> list = new ArrayList<Buffer>();
Iterator<Buffer> i = buffers.iterator();
while(i.hasNext()) {
Buffer b = i.next();
if(b.cid == cid)
list.add(b);
}
Collections.sort(list, new comparator());
return list;
}
} |
package net.Ox4a42.volksempfaenger.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "podcast.db";
private static final int DB_VERSION = 1;
public static class Podcast {
public static final String _TABLE = "podcast";
public static final String ID = BaseColumns._ID;
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String WEBSITE = "website";
private static String createSql() {
return String.format("CREATE TABLE \"%s\" (\n"
+ " \"%s\" INTEGER PRIMARY KEY AUTOINCREMENT,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT UNIQUE,\n"
+ " \"%s\" TEXT\n"
+ ")", _TABLE, ID, TITLE, DESCRIPTION, URL, WEBSITE);
}
}
public static class Episode {
public static final String _TABLE = "episode";
public static final String ID = BaseColumns._ID;
public static final String PODCAST = "podcast_id";
public static final String TITLE = "title";
public static final String DATE = "date";
public static final String URL = "url";
public static final String DESCRIPTION = "description";
private static String createSql() {
return String.format("CREATE TABLE \"%s\" (\n"
+ " \"%s\" INTEGER PRIMARY KEY AUTOINCREMENT,\n"
+ " \"%s\" INTEGER REFERENCES \"%s\" (\"%s\") ON DELETE CASCADE,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" INTEGER,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT\n"
+ ")", _TABLE, ID, PODCAST, Podcast._TABLE,
Podcast.ID, TITLE, DATE, URL, DESCRIPTION);
}
}
public static class Enclosure {
public static final String _TABLE = "enclosure";
public static final String ID = BaseColumns._ID;
public static final String EPISODE = "episode_id";
public static final String TITLE = "title";
public static final String URL = "url";
public static final String MIME = "mime"; // mime type
public static final String FILE = "file"; // path to file
public static final String SIZE = "size"; // file size
public static final String STATE = "state"; // see state constants below
public static final String DURATION_TOTAL = "duration_total"; // total duration in seconds
public static final String DURATION_LISTENED = "duration_listened"; // listened time in seconds
public static final int STATE_NEW = 0;
public static final int STATE_DOWNLOAD_QUEUED = 1;
public static final int STATE_DOWNLOADING = 2;
public static final int STATE_DOWNLOADED = 3;
public static final int STATE_LISTEN_QUEUED = 4;
public static final int STATE_LISTENING = 5;
public static final int STATE_LISTENED = 6;
public static final int STATE_DELETED = 7;
private static String createSql() {
return String.format("CREATE TABLE \"%s\" (\n"
+ " \"%s\" INTEGER PRIMARY KEY AUTOINCREMENT,\n"
+ " \"%s\" INTEGER REFERENCES \"%s\" (\"%s\") ON DELETE CASCADE,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" TEXT,\n"
+ " \"%s\" INTEGER,\n"
+ " \"%s\" INTEGER,\n"
+ " \"%s\" INTEGER,\n"
+ " \"%s\" INTEGER\n"
+ ")", _TABLE, ID,
EPISODE, Episode._TABLE, Episode.ID, TITLE, URL, MIME,
FILE, SIZE, STATE, DURATION_TOTAL, DURATION_LISTENED);
}
}
Context context;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("DbHelper", "onCreate()");
db.execSQL(Podcast.createSql());
db.execSQL(Episode.createSql());
db.execSQL(Enclosure.createSql());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Nothing to do here
}
} |
package net.java.sip.communicator.util;
import java.io.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
/**
* A utility class that allows to extract the text content of an HTML page
* stripped from all formatting tags.
*
* @author Emil Ivov <emcho at sip-communicator.org>
* @author Yana Stamcheva
* @author Lubomir Marinov
*/
public class Html2Text
{
/**
* The <tt>Logger</tt> used by the <tt>Html2Text</tt> class for logging
* output.
*/
private static final Logger logger
= Logger.getLogger(Html2Text.class);
/**
* The HTML parser used by {@link #extractText(String)} to parse HTML so
* that plain text can be extracted from it.
*/
private static HTMLParserCallback parser;
/**
* A utility method that allows to extract the text content of an HTML page
* stripped from all formatting tags. Method is synchronized to avoid
* concurrent access to the underlying <tt>HTMLEditorKit</tt>.
*
* @param html the HTML string that we will extract the text from.
* @return the text content of the <tt>html</tt> parameter.
*/
public static synchronized String extractText(String html)
{
if(html == null)
return null;
if (parser == null)
parser = new HTMLParserCallback();
try
{
StringReader in = new StringReader(html);
try
{
return parser.parse(in);
}
finally
{
in.close();
}
}
catch (Exception ex)
{
if (logger.isInfoEnabled())
logger.info("Failed to extract plain text from html="+html, ex);
return html;
}
}
/**
* The ParserCallback that will parse the HTML.
*/
private static class HTMLParserCallback
extends HTMLEditorKit.ParserCallback
{
/**
* The <tt>StringBuilder</tt> which accumulates the parsed text while it
* is being parsed.
*/
private StringBuilder sb;
/**
* Parses the text contained in the given reader.
*
* @param in the reader to parse.
* @return the parsed text
* @throws IOException thrown if we fail to parse the reader.
*/
public String parse(Reader in)
throws IOException
{
sb = new StringBuilder();
String s;
try
{
new ParserDelegator().parse(in, this, /* ignoreCharSet */ true);
s = sb.toString();
}
finally
{
/*
* Since the Html2Text class keeps this instance in a static
* reference, the field sb should be reset to null as soon as
* completing its goad in order to avoid keeping the parsed
* text in memory after it is no longer needed i.e. to prevent
* a memory leak. This method has been converted to return the
* parsed string instead of having a separate getter method for
* the parsed string for the same purpose.
*/
sb = null;
}
return s;
}
/**
* Appends the given text to the string buffer.
*
* @param text
* @param pos
*/
@Override
public void handleText(char[] text, int pos)
{
sb.append(text);
}
}
} |
package com.kkbox.toolkit.ui;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import com.kkbox.toolkit.listview.adapter.InfiniteViewPagerAdapter;
public class InfiniteViewPager extends ViewPager {
private OnInfiniteViewPagerPageChangeListener onInfiniteViewPagerPageChangeListener;
private int currentPosition = 0;
private boolean scrolled = false;
private boolean isLoopEnable = false;
public InfiniteViewPager(Context context) {
super(context);
setOnPageChangeListener(onPageChangeListener);
}
public InfiniteViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setOnPageChangeListener(onPageChangeListener);
}
@Override
public void setCurrentItem(int item, boolean smoothScroll) {
if (isLoopEnable) {
super.setCurrentItem(item + 1, smoothScroll);
} else {
super.setCurrentItem(item, smoothScroll);
}
}
@Override
public void setCurrentItem(int item) {
setCurrentItem(item, true);
}
@Override
public int getCurrentItem() {
if (isLoopEnable) {
final int index = super.getCurrentItem();
final int count = getAdapter().getCount();
if (index == 0) {
return count - 3;
} else if (index == count - 1) {
return 0;
} else {
return index - 1;
}
} else {
return super.getCurrentItem();
}
}
@Override
public void setAdapter(PagerAdapter adapter) {
super.setAdapter(adapter);
if (adapter instanceof InfiniteViewPagerAdapter) {
isLoopEnable = ((InfiniteViewPagerAdapter) adapter).isLoopEnabled();
if (isLoopEnable) {
setCurrentItem(0);
}
}
}
public void setOnPageChangeListener(OnInfiniteViewPagerPageChangeListener listener) {
onInfiniteViewPagerPageChangeListener = listener;
}
private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageSelected(int position) {
if (scrolled) {
InfiniteViewPagerAdapter adapter = (InfiniteViewPagerAdapter) getAdapter();
scrolled = false;
if (onInfiniteViewPagerPageChangeListener != null) {
onInfiniteViewPagerPageChangeListener.onLoopPageSelected(position);
}
if ((currentPosition > position) || (isLoopEnable && position == 0)) {
if (onInfiniteViewPagerPageChangeListener != null) {
onInfiniteViewPagerPageChangeListener.onPageScrollLeft();
}
} else if ((currentPosition < position) || (isLoopEnable && position == adapter.getCount() - 1)) {
if (onInfiniteViewPagerPageChangeListener != null) {
onInfiniteViewPagerPageChangeListener.onPageScrollRight();
}
}
}
currentPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
scrolled = true;
} else if (state == ViewPager.SCROLL_STATE_IDLE) {
scrolled = false;
if (isLoopEnable) {
final int count = getAdapter().getCount();
if (currentPosition == count - 1) {
//last to first
setCurrentItem(0, false);
currentPosition = 1;
} else if (currentPosition == 0) {
//first to last
setCurrentItem(count - 3, false);
currentPosition = count - 2;
}
}
}
}
};
} |
package com.larsbutler.gamedemo.core;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.List;
import com.larsbutler.gamedemo.math.Acceleration;
import com.larsbutler.gamedemo.math.Collision;
import com.larsbutler.gamedemo.math.MathUtil;
import com.larsbutler.gamedemo.math.RK4;
import com.larsbutler.gamedemo.math.State;
import com.larsbutler.gamedemo.models.Entity;
import com.larsbutler.gamedemo.models.Level;
import com.larsbutler.gamedemo.models.Player;
public class GameState implements KeyListener {
private Level level;
private Player player;
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
/**
* Do all physics and entity updates here.
*
* @param timeStepNanos
* Time delta (in ns) to simulate physics. For example, if
* timeStepNanos == 1/60 sec, we do physics updates for 1/60 sec.
*/
public void update(long prevTimeStep, long timeStepNanos) {
double t = (double)prevTimeStep / Kernel.NANOS_PER_SECOND;
double dt = (double)timeStepNanos / Kernel.NANOS_PER_SECOND;
updatePlayer(player, dt);
move(player, t, dt);
}
public static void updatePlayer(Player p, double dt) {
State state = p.getXState();
if (p.isLeft() && p.isRight()) {
state.v = 0.0;
}
else if (p.isLeft()) {
state.v += -(Player.CEL_PER_SECOND * dt);
// Cap the movement speed to the maximum allowed
if (state.v <= -Player.MAX_XVEL_PER_UPDATE) {
state.v = -Player.MAX_XVEL_PER_UPDATE;
}
}
else if (p.isRight()) {
state.v += (Player.CEL_PER_SECOND * dt);
// Cap the movement speed to the maximum allowed
if (state.v >= Player.MAX_XVEL_PER_UPDATE) {
state.v = Player.MAX_XVEL_PER_UPDATE;
}
}
else {
// we're moving right
// reduce the overall speed
if (state.v > 0.0) {
state.v += -(Player.CEL_PER_SECOND * dt);
if (state.v < 0.0) {
state.v = 0.0;
}
}
// we're moving left
// reduce the overall speed
else if (state.v < 0.0) {
state.v += (Player.CEL_PER_SECOND * dt);
if (state.v > 0.0) {
state.v = 0.0;
}
}
}
}
public void move(Entity e, double t, double dt) {
State currentXState = e.getXState();
State currentYState = e.getYState();
e.setPrevXState(currentXState);
e.setPrevYState(currentYState);
// All of the solid tiles we can collide with:
List<Rectangle2D> levelHitBoxes = level.tileHitBoxes();
double correction = 0.0;
// Move one axis at a time, and check for collisions after each.
e.setXState(
RK4.integrate(currentXState, t, dt, Acceleration.EMPTY));
for (Rectangle2D box : levelHitBoxes) {
correction = Collision.getXCorrection(e, box);
if (correction != 0.0) {
e.getXState().p += correction;
// Since we hit something, zero the velocity
// on this axis:
e.getXState().v = 0.0;
}
}
e.setYState(
RK4.integrate(currentYState, t, dt, Acceleration.GRAVITY_ONLY));
boolean floorColl = false;
for (Rectangle2D box : levelHitBoxes) {
correction = Collision.getYCorrection(e, box);
if (correction != 0.0) {
e.getYState().p = (double)(float)(e.getYState().p + correction);
// e.getYState().p += correction;
// if we hit a "floor",
// reset `canJump` status:
if (e.getYState().v > 0.0) {
// we were falling
floorColl = true;
}
// Since we hit something, zero the velocity
// on this axis:
e.getYState().v = 0.0;
}
}
e.setCanJump(floorColl);
}
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
switch (kc) {
case KeyEvent.VK_LEFT:
player.setLeft(true);
break;
case KeyEvent.VK_RIGHT:
player.setRight(true);
break;
case KeyEvent.VK_SPACE:
player.jump();
break;
}
}
public void keyReleased(KeyEvent e) {
int kc = e.getKeyCode();
switch (kc) {
case KeyEvent.VK_LEFT:
player.setLeft(false);
break;
case KeyEvent.VK_RIGHT:
player.setRight(false);
break;
}
}
public void keyTyped(KeyEvent e) {}
} |
package net.milkycraft.Listeners;
import net.milkycraft.Spawnegg;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
public class EnchantListener implements Listener {
/*
* Class Tested and working
*/
Spawnegg plugin;
public EnchantListener(Spawnegg instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGH)
public void onEnchantAttempt(PrepareItemEnchantEvent e) {
if(plugin.getConfig().getBoolean("Disable.Enchanting") &&
!e.getEnchanter().hasPermission("entitymanager.enchanting")) {
e.setCancelled(true);
return;
}
}
} |
package org.ofbiz.base.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* SCIPIO: Used to delay property message evaluation.
* <p>
* New class (moved to org.ofbiz.base.util 2017-02-08).
*/
@SuppressWarnings("serial")
public abstract class PropertyMessage implements Serializable {
public static final String module = PropertyMessage.class.getName();
protected abstract String getMessageImpl(Locale locale);
public static Locale getDefPropLocale() {
return UtilProperties.getFallbackLocale();
}
public static Locale getDefSysLocale() {
return Locale.getDefault();
}
public static Locale getLogLocale() {
return Locale.ENGLISH;
}
public static Locale getDefExLocale() {
return Locale.ENGLISH;
}
/**
* Gets message in the specified locale, or in the default/fallback property locale if null ({@link UtilProperties#getFallbackLocale()}).
*/
public String getMessage(Locale locale) {
return getMessageImpl(locale != null ? locale : getDefPropLocale());
}
/**
* Gets message in the locale of the named locale field of context, or in the default/fallback property locale if null ({@link UtilProperties#getFallbackLocale()}).
*/
public String getMessage(Map<String, ?> context, String localeFieldName) {
return getMessage((Locale) context.get(localeFieldName));
}
/**
* Gets message in the locale of the common "locale" field of context, or in the default/fallback property locale if null ({@link UtilProperties#getFallbackLocale()}).
*/
public String getMessage(Map<String, ?> context) {
return getMessage(context, "locale");
}
/**
* Gets message in default/fallback locale specified by locale.properties.fallback in general.properties ({@link UtilProperties#getFallbackLocale()}).
*/
public String getDefPropLocaleMessage() {
return getMessage(getDefPropLocale());
}
/**
* Gets message in default system locale ({@link Locale#getDefault()}).
*/
public String getDefSysLocaleMessage() {
return getMessage(getDefSysLocale());
}
/**
* Gets message in the log language (always {@link Locale#ENGLISH} in scipio/ofbiz).
*/
public String getLogMessage() {
return getMessage(getLogLocale());
}
/**
* Gets message in the exception language (always {@link Locale#ENGLISH} in scipio/ofbiz).
*/
public String getDefExLocaleMessage() {
return getMessage(getDefExLocale());
}
/**
* Gets english message.
*/
public String getEnMessage() {
return getMessage(Locale.ENGLISH);
}
/**
* Gets message in default sys locale.
* @deprecated 2017-11: ambiguous; use appropriate method above instead ({@link #getDefaultSystemLocaleMessage}, {@link #getLogMessage}, etc.).
*/
@Deprecated
public String getMessage() {
return getMessage(Locale.getDefault());
}
/**
* Gets English message for debugging purposes - AVOID this method - use {@link #getMessage} or others above.
*/
@Override
public String toString() {
return getEnMessage();
}
public static List<String> getMessages(Collection<PropertyMessage> propMsgs, Locale locale) {
if (propMsgs == null) return null;
List<String> msgs = new ArrayList<>(propMsgs.size());
for(PropertyMessage propMsg : propMsgs) {
if (propMsg == null) continue;
String msg = propMsg.getMessage(locale);
if (msg != null) msgs.add(msg);
}
return msgs;
}
public static List<String> getDefPropLocaleMessages(Collection<PropertyMessage> propMsgs) {
return getMessages(propMsgs, getDefPropLocale());
}
public static List<String> getDefSysLocaleMessages(Collection<PropertyMessage> propMsgs) {
return getMessages(propMsgs, getDefSysLocale());
}
public static List<String> getLogMessages(Collection<PropertyMessage> propMsgs) {
return getMessages(propMsgs, getLogLocale());
}
public static List<String> getDefExLocaleMessages(Collection<PropertyMessage> propMsgs) {
return getMessages(propMsgs, getDefExLocale());
}
public static PropertyMessage make(String resource, String propertyName, Map<String, ?> propArgs, String prefix, String suffix) {
return new DynamicPropertyMessage(resource, propertyName, propArgs, prefix, suffix);
}
public static PropertyMessage make(String resource, String propertyName, Map<String, ?> propArgs) {
return new DynamicPropertyMessage(resource, propertyName, propArgs, null, null);
}
public static PropertyMessage make(String resource, String propertyName, String prefix, String suffix) {
return new DynamicPropertyMessage(resource, propertyName, null, prefix, suffix);
}
public static PropertyMessage make(String resource, String propertyName) {
return new DynamicPropertyMessage(resource, propertyName, null, null, null);
}
public static PropertyMessage makeFromStatic(String message) {
return new StaticPropertyMessage(message);
}
public static PropertyMessage makeFromException(Throwable t) {
if (t instanceof PropertyMessageEx) {
return new PropertyExceptionPropertyMessage((PropertyMessageEx) t, true);
} else {
return new StandardExceptionPropertyMessage(t);
}
}
/**
* Gets the null-returning instance, can be used to both return null values and as a special
* token value.
*/
public static PropertyMessage getNull() {
return NullPropertyMessage.INSTANCE;
}
/**
* Gets the empty-string-returning instance, can be used to return empty values,
* but shouldn't be relied on as a token value.
*/
public static PropertyMessage getEmpty() {
return EmptyPropertyMessage.INSTANCE;
}
/**
* Tests if this is the special null instance, {@link NullPropertyMessage}.
*/
public final boolean isNullInst() {
return this == NullPropertyMessage.INSTANCE;
}
/**
* Tests if this is specifically the empty instance, {@link EmptyPropertyMessage}.
*/
public final boolean isEmptyInst() {
return this == EmptyPropertyMessage.INSTANCE;
}
/**
* Tests if this is an always-null returning instance, best-effort.
*/
public boolean isAlwaysNull() {
return false;
}
/**
* Tests if this is an always-empty or always-null returning instance, best-effort.
*/
public boolean isAlwaysEmpty() {
return false;
}
public static PropertyMessage makeAuto(Object message, boolean strict) {
if (message == null) return null;
else if (message instanceof PropertyMessage) return (PropertyMessage) message;
else if (message instanceof String) return makeFromStatic((String) message);
else if (message instanceof Throwable) return makeFromException((Throwable) message);
else {
if (strict) throw new IllegalArgumentException("cannot convert object to PropertyMessage, unknown type: " + message.getClass().getName());
else {
try {
return new StaticPropertyMessage(message.toString());
} catch(Throwable t) {
// this will likely never happen, it's just to be safe in case toString() explodes on some instance
Debug.logError(t, "PropertyMessage.makeAuto: Unexpected error converting message to PropertyMessage instance (error message swallowed): " + t.getMessage(), module);
return null;
}
}
}
}
/**
* Makes an appropriate PropertyMessage instance for the object instance type.
* Does not throw exceptions.
* @param message the source message object
*/
public static PropertyMessage makeAutoSafe(Object message) {
return makeAuto(message, false);
}
public static List<PropertyMessage> makeListAuto(Collection<?> messages, boolean strict) {
if (messages == null) return null;
List<PropertyMessage> propMsgs = new ArrayList<>(messages.size());
for(Object msg : messages) {
if (msg == null) {
if (strict) {
throw new NullPointerException("PropertyMessage.makeAutoFromList: encountered null message in list");
} else {
Debug.logWarning("PropertyMessage.makeAutoFromList: null message encountered; filtering out (caller may not be creating error messages properly)", module);
continue;
}
}
PropertyMessage propMsg = makeAuto(msg, strict);
if (propMsg != null) {
propMsgs.add(propMsg);
}
}
return propMsgs;
}
/**
* SCIPIO: Returns a new list where each given message is converted to a PropertyMessage instance
* if it is not already one.
* Does not throw exceptions.
* @param messages the source messages objects
*/
public static List<PropertyMessage> makeListAutoSafe(Collection<?> messages) {
return makeListAuto(messages, false);
}
/**
* Makes a property message list from either a single message or list.
* If messageOrList is null, this will return null (not an empty list).
*/
public static List<PropertyMessage> makeListAuto(Object messageOrList, boolean strict) {
if (messageOrList instanceof Collection) {
return makeListAuto((Collection<?>) messageOrList, strict);
} else {
PropertyMessage msg = makeAuto(messageOrList, strict);
if (msg == null) return null;
List<PropertyMessage> list = new ArrayList<>();
list.add(msg);
return list;
}
}
/**
* Makes a property message list from either a single message or list.
* If messageOrList is null, this will return null (not an empty list).
* Does not throw exceptions.
*/
public static List<PropertyMessage> makeListAutoSafe(Object messageOrList) {
return makeListAuto(messageOrList, false);
}
public static class NullPropertyMessage extends PropertyMessage {
private static final NullPropertyMessage INSTANCE = new NullPropertyMessage();
private NullPropertyMessage() {}
@Override
protected String getMessageImpl(Locale locale) {
return null;
}
@Override
public boolean isAlwaysNull() {
return true;
}
@Override
public boolean isAlwaysEmpty() {
return true;
}
}
public static class EmptyPropertyMessage extends PropertyMessage {
private static final String EMPTY_STRING = "";
private static final EmptyPropertyMessage INSTANCE = new EmptyPropertyMessage();
private EmptyPropertyMessage() {}
@Override
protected String getMessageImpl(Locale locale) {
return EMPTY_STRING;
}
@Override
public boolean isAlwaysNull() {
return false;
}
@Override
public boolean isAlwaysEmpty() {
return true;
}
}
public static class StaticPropertyMessage extends PropertyMessage {
private final String message;
protected StaticPropertyMessage(String message) {
this.message = message;
}
@Override
protected String getMessageImpl(Locale locale) {
return message;
}
@Override
public boolean isAlwaysNull() {
return (message == null);
}
@Override
public boolean isAlwaysEmpty() {
return (message == null || message.isEmpty());
}
}
public abstract static class ExceptionPropertyMessage extends PropertyMessage {
public abstract Throwable getException();
}
/**
* Wraps an exception and returns its non-localized {@link Exception#getMessage()} value.
*/
public static class StandardExceptionPropertyMessage extends ExceptionPropertyMessage {
private final Throwable t;
protected StandardExceptionPropertyMessage(Throwable t) {
this.t = t;
}
@Override
protected String getMessageImpl(Locale locale) {
return getException().getMessage();
}
@Override
public Throwable getException() {
return t;
}
}
/**
* Wraps a {@link PropertyMessageEx}-implementing exception and delegates to its
* localized PropertyMessage message via {@link PropertyMessageEx#getPropertyMessage()}.
* NOTE: if useFallback true, it will use {@link Exception#getMessage()} if property message
* gives null.
*/
public static class PropertyExceptionPropertyMessage extends ExceptionPropertyMessage {
private final PropertyMessageEx propMsgEx;
private final boolean useFallback;
protected PropertyExceptionPropertyMessage(PropertyMessageEx propMsgEx, boolean useFallback) {
this.propMsgEx = propMsgEx;
this.useFallback = useFallback;
}
@Override
protected String getMessageImpl(Locale locale) {
String msg = propMsgEx.getPropertyMessage().getMessage(locale);
if (msg == null && useFallback) {
msg = getException().getMessage();
}
return msg;
}
@Override
public Throwable getException() {
return (Throwable) propMsgEx;
}
}
public static class DynamicPropertyMessage extends PropertyMessage {
private final String resource;
private final String propertyName;
private final Map<String, ?> propArgs;
private final String prefix;
private final String suffix;
protected DynamicPropertyMessage(String resource, String propertyName, Map<String, ?> propArgs, String prefix, String suffix) {
this.resource = resource;
this.propertyName = propertyName;
this.propArgs = propArgs;
this.prefix = prefix;
this.suffix = suffix;
}
@Override
protected String getMessageImpl(Locale locale) {
if (propArgs != null) {
return (prefix != null ? prefix : "") +
UtilProperties.getMessage(resource, propertyName, propArgs, locale) + (suffix != null ? suffix : "");
} else {
return (prefix != null ? prefix : "") +
UtilProperties.getMessage(resource, propertyName, locale) + (suffix != null ? suffix : "");
}
}
}
} |
package com.localhop.network;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.List;
import android.app.Activity;
import android.widget.Toast;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* Task that connects to a server running HERMIT-web and simulates HERMIT commands
* by using HTTP GET and POST requests.
*/
public abstract class HttpServerRequest<A extends Activity, Result> extends AsyncActivityTask<A, String, Void, Result> {
public static String DUMMY_URL = "http://ip.jsontest.com/";
private HttpRequest mRequest;
private String mErrorMessage;
private List<NameValuePair> mData;
/**
* Constructs a new instance. The constructor is not the place to put any input
* {@link JSONObject}s (do that in {@link android.os.AsyncTask#execute(JSONObject...)
* execute(JSONObject...)} instead).
*
* @param console reference to the current console.
*/
public HttpServerRequest(A activity, HttpRequest request, List<NameValuePair> data) {
super(activity);
mRequest = request;
mData = data;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Result doInBackground(String... params) {
HttpClient httpClient = null;
HttpResponse httpResponse = null;
String responseStr = null;
final String url = params[0];
try {
final HttpParams httpParams = new BasicHttpParams();
//Set timeout length to 10 seconds
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
httpClient = new DefaultHttpClient(httpParams);
HttpUriRequest request = null;
if (mRequest.equals(HttpRequest.GET)) {
request = new HttpGet(url);
} else if (mRequest.equals(HttpRequest.POST)) {
final HttpPost httpPost = new HttpPost(url);
if (mData != null) {
try {
httpPost.setEntity(new UrlEncodedFormEntity(mData, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
request = httpPost;
}
if (!isCancelled()) {
httpResponse = httpClient.execute(request);
}
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String entity = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8).trim();
if (entity != null) {
responseStr = entity;
}
} else {
throw new HttpException("Error code " + httpResponse.getStatusLine().getStatusCode());
}
} catch (HttpException e) {
return cancelResult(e, "ERROR: server problem (" + httpResponse.getStatusLine().getStatusCode() + ").");
} catch (HttpHostConnectException e) {
return cancelResult(e, "ERROR: server connection refused.");
} catch (ClientProtocolException e) {
return cancelResult(e, "ERROR: client protocol problem.");
} catch (NoHttpResponseException e) {
return cancelResult(e, "ERROR: the target server failed to respond.");
} catch (ConnectTimeoutException e) {
return cancelResult(e, "ERROR: the server connection timed out.");
} catch (SocketTimeoutException e) {
return cancelResult(e, "ERROR: the server connection timed out.");
} catch (IOException e) {
return cancelResult(e, "ERROR: I/O problem.");
} finally {
httpClient.getConnectionManager().shutdown();
}
return onResponse(responseStr);
}
@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
}
@Override
protected void onCancelled(Result error) {
super.onCancelled(error);
if (mErrorMessage != null) {
Toast.makeText(getActivity(), mErrorMessage, Toast.LENGTH_SHORT).show();
}
}
private Result cancelResult(Exception error, String errorMsg) {
error.printStackTrace();
mErrorMessage = errorMsg;
cancel(true);
return null;
}
protected abstract Result onResponse(String response);
protected String getErrorMessage() {
return mErrorMessage;
}
protected void setErrorMessage(String message) {
mErrorMessage = message;
}
} |
package com.maddyhome.idea.vim.common;
import com.maddyhome.idea.vim.command.SelectionType;
import com.maddyhome.idea.vim.helper.StringHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.util.Comparator;
import java.util.List;
/**
* Represents a register.
*/
public class Register {
private char name;
@NotNull private final SelectionType type;
@NotNull private final List<KeyStroke> keys;
public Register(char name, @NotNull SelectionType type, @NotNull String text) {
this.name = name;
this.type = type;
this.keys = StringHelper.stringToKeys(text);
}
public Register(char name, @NotNull SelectionType type, @NotNull List<KeyStroke> keys) {
this.name = name;
this.type = type;
this.keys = keys;
}
public void rename(char name) {
this.name = name;
}
/**
* Get the name the register is assigned to.
*/
public char getName() {
return name;
}
/**
* Get the register type.
*/
@NotNull
public SelectionType getType() {
return type;
}
/**
* Get the text in the register.
*/
@Nullable
public String getText() {
final StringBuilder builder = new StringBuilder();
for (KeyStroke key : keys) {
final char c = key.getKeyChar();
if (c == KeyEvent.CHAR_UNDEFINED) {
return null;
}
builder.append(c);
}
return builder.toString();
}
/**
* Get the sequence of keys in the register.
*/
@NotNull
public List<KeyStroke> getKeys() {
return keys;
}
/**
* Append the supplied text to any existing text.
*/
public void addText(@NotNull String text) {
addKeys(StringHelper.stringToKeys(text));
}
public void addKeys(@NotNull List<KeyStroke> keys) {
this.keys.addAll(keys);
}
public static class KeySorter<V> implements Comparator<V> {
public int compare(V o1, V o2) {
Register a = (Register)o1;
Register b = (Register)o2;
return Character.compare(a.name, b.name);
}
}
} |
package com.poomoo.edao.activity;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.poomoo.edao.R;
import com.poomoo.edao.application.eDaoClientApplication;
import com.poomoo.edao.config.eDaoClientConfig;
import com.poomoo.edao.model.ResponseData;
import com.poomoo.edao.model.UserInfoData;
import com.poomoo.edao.service.Get_UserInfo_Service;
import com.poomoo.edao.util.HttpCallbackListener;
import com.poomoo.edao.util.HttpUtil;
import com.poomoo.edao.util.Utity;
import com.poomoo.edao.widget.MessageBox_YES;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
*
* @ClassName LoginActivity
* @Description TODO
* @author
* @date 2015-7-31 10:30:33
*/
public class LoginActivity extends BaseActivity implements OnClickListener {
private EditText editText_phone, editText_password;
private Button button_login;
private TextView textView_regist, textView_forget_password;
private String phoneNum = "", passWord = "";
private Gson gson = new Gson();
private MessageBox_YES box_YES;
// private MessageBox_YESNO box_YESNO;
private ProgressDialog progressDialog = null;
private UserInfoData loginResData = null;
private SharedPreferences loginsp;
private Editor editor = null;
private eDaoClientApplication application = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
setImmerseLayout(findViewById(R.id.navigation_fragment));
application = (eDaoClientApplication) getApplication();
init();
}
private void init() {
// TODO
editText_phone = (EditText) findViewById(R.id.login_editText_phone);
editText_password = (EditText) findViewById(R.id.login_editText_password);
button_login = (Button) findViewById(R.id.login_btn_login);
textView_regist = (TextView) findViewById(R.id.login_textView_regist);
textView_forget_password = (TextView) findViewById(R.id.login_textView_forget_password);
button_login.setOnClickListener(this);
textView_regist.setOnClickListener(this);
textView_forget_password.setOnClickListener(this);
loginsp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
editor = loginsp.edit();
if (!TextUtils.isEmpty(loginsp.getString("tel", "")))
editText_phone.setText(loginsp.getString("tel", ""));
// if (!TextUtils.isEmpty(loginsp.getString("passWord", ""))) {
// passWord = loginsp.getString("passWord", "");
// // AES
// try {
// passWord = Utity.decrypt(eDaoClientConfig.key, passWord);
// } catch (Exception e) {
// System.out.println(":" + e.getMessage());
// Utity.showToast(getApplicationContext(), ":" + e.getMessage());
// passWord = "";
// editText_password.setText(passWord);
}
@Override
public void onClick(View v) {
// TODO
switch (v.getId()) {
case R.id.login_btn_login:
login();
break;
case R.id.login_textView_regist:
openActivity(ProtocolActivity.class);
break;
case R.id.login_textView_forget_password:
phoneNum = editText_phone.getText().toString().trim();
if (TextUtils.isEmpty(phoneNum)) {
Utity.showToast(getApplicationContext(), "!");
return;
}
if (phoneNum.length() != 11) {
Utity.showToast(getApplicationContext(), ",!");
return;
}
checkTel();
break;
}
}
private void login() {
if (checkInput()) {
Map<String, String> data = new HashMap<String, String>();
data.put("bizName", "10000");
data.put("method", "10001");
data.put("tel", phoneNum);
data.put("password", passWord);
showProgressDialog("...");
HttpUtil.SendPostRequest(gson.toJson(data), eDaoClientConfig.url, new HttpCallbackListener() {
@Override
public void onFinish(final ResponseData responseData) {
// TODO
closeProgressDialog();
System.out.println("onFinish");
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO
if (responseData.getRsCode() != 1) {
box_YES = new MessageBox_YES(LoginActivity.this);
box_YES.showDialog(responseData.getMsg(), null);
} else {
loginResData = new UserInfoData();
loginResData = gson.fromJson(responseData.getJsonData(), UserInfoData.class);
editor.putString("userId", loginResData.getUserId());
editor.putString("realName", loginResData.getRealName());
editor.putString("tel", loginResData.getTel());
editor.putString("type", loginResData.getType());
editor.putString("realNameAuth", loginResData.getRealNameAuth());
editor.putString("payPwdValue", loginResData.getPayPwdValue());
try {
passWord = Utity.encrypt(eDaoClientConfig.key, passWord);
} catch (Exception e) {
Utity.showToast(getApplicationContext(), ":" + e.getMessage());
passWord = "";
}
// editor.putString("passWord", passWord);
editor.putString("quickmarkPic", loginResData.getQuickmarkPic());
editor.putBoolean("isLogin", true);
editor.commit();
application.setRealName(loginResData.getRealName());
application.setTel(loginResData.getTel());
application.setUserId(loginResData.getUserId());
application.setType(loginResData.getType());
application.setRealNameAuth(loginResData.getRealNameAuth());
application.setPayPwdValue(loginResData.getPayPwdValue());
application.setQuickmarkPic(loginResData.getQuickmarkPic());
startService(new Intent(LoginActivity.this, Get_UserInfo_Service.class));
LoginActivity.this
.startActivity(new Intent(LoginActivity.this, NavigationActivity.class));
LoginActivity.this.finish();
System.out.println("");
}
}
});
}
@Override
public void onError(final Exception e) {
// TODO
closeProgressDialog();
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO
Utity.showToast(getApplicationContext(), eDaoClientConfig.checkNet);
}
});
}
});
}
}
/**
*
*
* @Title: checkTel
* @Description: TODO
* @author
* @return
* @return void
* @throws @date
* 201592311:45:02
*/
private void checkTel() {
Map<String, String> data = new HashMap<String, String>();
data.put("bizName", "10000");
data.put("method", "10002");
data.put("tel", phoneNum);
showProgressDialog("...");
HttpUtil.SendPostRequest(gson.toJson(data), eDaoClientConfig.url, new HttpCallbackListener() {
@Override
public void onFinish(final ResponseData responseData) {
// TODO
closeProgressDialog();
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO
if (responseData.getRsCode() != 1) {
Bundle pBundle = new Bundle();
pBundle.putString("type", "3");
pBundle.putString("tel", phoneNum);
openActivity(PassWordManageActivity.class, pBundle);
} else {
Utity.showToast(getApplicationContext(), phoneNum + "");
}
}
});
}
@Override
public void onError(Exception e) {
// TODO
closeProgressDialog();
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO
Utity.showToast(getApplicationContext(), "");
}
});
}
});
}
/**
*
*
* @Title: checkInput
* @Description: TODO
* @author
* @return
* @return boolean
* @throws @date
* 2015-8-1210:11:38
*/
private boolean checkInput() {
phoneNum = editText_phone.getText().toString().trim();
if (TextUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
editText_phone.setText("");
editText_phone.setFocusable(true);
editText_phone.requestFocus();
Utity.showToast(getApplicationContext(), ",");
return false;
}
passWord = editText_password.getText().toString().trim();
if (TextUtils.isEmpty(passWord)) {
editText_password.setFocusable(true);
editText_password.requestFocus();
Utity.showToast(getApplicationContext(), "");
return false;
}
return true;
}
/**
*
*
* @Title: showProgressDialog
* @Description: TODO
* @author
* @return
* @return void
* @throws @date
* 2015-8-121:23:53
*/
private void showProgressDialog(String msg) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(msg);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
}
progressDialog.show();
}
/**
*
*
* @Title: closeProgressDialog
* @Description: TODO
* @author
* @return
* @return void
* @throws @date
* 2015-8-121:24:43
*/
private void closeProgressDialog() {
if (progressDialog != null)
progressDialog.dismiss();
}
} |
package com.puntodeventa.services.DAO;
import com.puntodeventa.global.Entity.Corte;
import com.puntodeventa.global.Entity.Sesion;
import com.puntodeventa.global.Entity.Usuario;
import com.puntodeventa.global.Entity.Venta;
import com.puntodeventa.global.Enum.PrintType;
import com.puntodeventa.global.Util.LogHelper;
import com.puntodeventa.global.Util.Util;
import com.puntodeventa.global.printservice.printService;
import com.puntodeventa.global.report.viewer.printCorte;
import com.puntodeventa.mvc.Controller.VentaLogic;
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.icepdf.core.exceptions.PDFSecurityException;
/**
*
* @author Fortunato Hdez Hdez
*/
public class CorteDAO {
LogHelper objLog = new LogHelper("CorteDAO");
static printCorte pCorte = new printCorte();
private Session session;
private Transaction tx;
private List<Corte> listCorte = new ArrayList<>();
byte[] pdfBuffer = null;
//Metodo: Inicializa la operacion para procesos en la base de datos
private void iniciaOperacion() {
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
} catch (HibernateException ex) {
objLog.Log(ex.getMessage());
}
}
// Metodo: Obtenemos el error que podria ocacionar an cada metodo
private void manejaException(HibernateException he) throws HibernateException {
tx.rollback();
objLog.Log(he.getMessage());
throw new HibernateException("Ocurrio un error en la capa de acceso a datos. Error: " + he.getMessage());
}
//Metodo guarda corte
public int saveCorte(Corte corte) {
int idFolio = 0;
try {
this.iniciaOperacion();
idFolio = Integer.parseInt(session.save(corte).toString());
tx.commit();
} catch (HibernateException he) {
this.manejaException(he);
throw he;
} finally {
session.close();
}
return idFolio;
}
/**
* Actualiza los datos de la tabla Ventas
*/
public void updateCorte(Corte corte) throws HibernateException {
try {
this.iniciaOperacion();
session.update(corte);
tx.commit();
} catch (HibernateException he) {
this.manejaException(he);
throw he;
} finally {
session.close();
}
}
/**
* Elimina registro de la Tabla Corte
*/
public void deleteCorte(Corte corte) {
try {
this.iniciaOperacion();
session.delete(corte);
tx.commit();
} catch (HibernateException he) {
this.manejaException(he);
throw he;
} finally {
session.close();
}
}
/**
* Metodo que devuelve un objeto Corte
*/
public Corte selectCorte(int idCorte) {
Corte corte = null;
try {
this.iniciaOperacion();
corte = (Corte) session.get(Corte.class, corte);
} catch (HibernateException he) {
this.manejaException(he);
throw he;
} finally {
session.close();
}
return corte;
}
public boolean processCut(double efvoInicial, double efvoCaja) throws PDFSecurityException {
boolean returnValue = false;
Corte corte = new Corte();
List ventas = null;
Usuario user = null;
Sesion sesion = null;
try {
sesion = Util.getCurrentSesion();
user = Util.getCurrentUser();
} catch (Exception e) {
objLog.Log("Cuse: Error while getting current Session or User" + e.getMessage());
}
try {
if (user != null && sesion != null) {
this.iniciaOperacion();
ventas = session.createCriteria(Venta.class).add(Restrictions.between("fecha", sesion.getStartDate(), sesion.getEndDate())).add(Restrictions.eq("usuario", user)).list();
this.tx.commit();
}
} catch (HibernateException hibernateException) {
objLog.Log("Cause: Error while getting the Ventas list from DB. " + hibernateException.getMessage());
} catch (Exception ex) {
objLog.Log(ex.getMessage());
}
try {
double total = 0;
try {
VentaLogic vtaLgc = new VentaLogic();
total = vtaLgc.getTotalUserTurn();
} catch (Exception e) {
objLog.Log("Error while getting total of the current user from DB. " + e.getMessage());
}
if (ventas != null) {
int elements = ventas.size();
Venta firstElm, secElem;
if (!ventas.isEmpty()) {
firstElm = (Venta) ventas.get(0);
secElem = (Venta) ventas.get(ventas.size() - 1);
corte.setEfvoCaja(efvoCaja);
corte.setEfvoInicial(efvoInicial);
corte.setFecha(new Date());
corte.setId_usuario(user);
corte.setNumero_de_ventas(elements);
// corte.setTotal_preciocompra(orders);
corte.setTotal_precioventa(total);
corte.setVentafolio_from(firstElm.getIdFolio());
corte.setVentafolio_to(secElem.getIdFolio());
corte.setTotal_corte(total);
}
}
int id_folio = 0;
try {
id_folio = this.saveCorte(corte);
} catch (Exception e) {
objLog.Log("Error while savinging Corte. " + e.getMessage());
}
try {
pdfBuffer = pCorte.printCortepdfBuffer(corte, user);
} catch (Exception e) {
objLog.Log("Error while exportTopdf in disco. " + e.getMessage());
}
try {
if (pdfBuffer != null){
printService.printArrayPdf(pdfBuffer);
}else{
objLog.Log("pdfBuffer is null");
}
} catch (Exception ex) {
objLog.Log("Error while printing Corte. " + ex.getMessage());
}
} catch (Exception e) {
objLog.Log("Error while processing Corte. " + e.getMessage());
}
return returnValue;
}
} |
package org.uberfire.client.util;
import org.uberfire.client.workbench.panels.SplitPanel;
import org.uberfire.debug.Debug;
import org.uberfire.workbench.model.CompassPosition;
import org.uberfire.workbench.model.PanelDefinition;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.Widget;
public class Layouts {
/**
* Sets the CSS on the given widget so it automatically fills the available space, rather than being sized based on
* the amount of space required by its contents. This tends to be useful when building a UI that always fills the
* available space on the screen, as most desktop application windows do.
* <p>
* To achieve this, the element is given relative positioning with top and left set to 0px and width and height set
* to 100%. This makes the widget fill its nearest ancestor which has relative or absolute positioning. This
* technique is compatible with GWT's LayoutPanel system. Note that, like LayoutPanels, this only works if the host
* page is in standards mode (has a {@code <!DOCTYPE html>} header).
*
* @param w
* the widget that should always fill its available space, rather than being sized to fit its contents.
*/
public static void setToFillParent( Widget w ) {
Element e = w.getElement();
Style s = e.getStyle();
s.setPosition( Position.RELATIVE );
s.setTop( 0.0, Unit.PX );
s.setLeft( 0.0, Unit.PX );
s.setWidth( 100.0, Unit.PCT );
s.setHeight( 100.0, Unit.PCT );
}
/**
* Returns a multi-line string detailing layout information about the given widget and each of its ancestors in the
* widget tree.
*
* @param w the widget to start at. Null is permitted, and results in this method returning an empty string.
* @return information about w and its ancestors, one widget per line.
*/
public static String getContainmentHierarchy( Widget w ) {
return getContainmentHierarchy( w, false );
}
/**
* Returns a multi-line string detailing layout information about the given widget and each of its ancestors in the
* widget tree, optionally setting debug IDs on each widget to assist in locating them in browser DOM explorer
* tools.
*
* @param w
* the widget to start at. Null is permitted, and results in this method returning an empty string.
* @param setDebugIds
* if true, the element and each of its ancestors will have its ID set to
* <code>"containment-parent-<i>depth</i>"</code>, where depth is 0 for the given widget, 1 for
* its parent, 2 for its grandparent, and so on. This ID will replace any ID that was previously set on
* the element, so it may break some CSS and even javascript functionality. Use with caution.
* @return information about w and its ancestors, one widget per line.
*/
public static String getContainmentHierarchy( Widget w, boolean setDebugIds ) {
StringBuilder sb = new StringBuilder();
int depth = 0;
while ( w != null ) {
if ( setDebugIds ) {
w.getElement().setId( "containment-parent-" + depth );
}
sb.append( " " + depth + " - " + widgetInfo( w ) );
w = w.getParent();
depth++;
}
return sb.toString();
}
private static String widgetInfo( Widget w ) {
String widgetInfo;
try {
String id = w.getElement().getId();
widgetInfo = w.getOffsetWidth() + "x" + w.getOffsetHeight() + " - " +
Debug.objectId( w ) +
(id != null && id.length() > 0 ? " id=" + id : "" ) +
(w instanceof SplitPanel ? " divider at " + ((SplitPanel) w).getFixedWidgetSize() : "") +
(w instanceof RequiresResize ? " RequiresResize" : "") +
(w instanceof ProvidesResize ? " ProvidesResize" : "") +
" position: " + w.getElement().getStyle().getPosition() + "\n";
} catch ( Throwable t ) {
widgetInfo = "?x? - " +
Debug.objectId( w ) +
": " + t.toString() + "\n";
}
return widgetInfo;
}
/**
* Returns a multi-line string detailing layout information about the given widget and each of its descendants in
* the widget tree.
*
* @param w
* the widget to start at. Null is permitted.
* @return information about w and its descendants, one widget per line. Each line is indented with leading spaces
* to illustrate the containment hierarchy.
*/
public static String getContainedHierarchy( final Widget startAt ) {
IndentedLineAccumulator result = new IndentedLineAccumulator();
getContainedHierarchyRecursively( startAt, 0, result );
return result.toString();
}
private static void getContainedHierarchyRecursively( final Widget startAt,
int depth,
IndentedLineAccumulator result ) {
if ( startAt == null ) {
result.append( depth,
"(null)" );
return;
}
result.append( depth,
widgetInfo( startAt ) );
if ( startAt instanceof HasWidgets ) {
for ( Widget child : ((HasWidgets) startAt) ) {
getContainedHierarchyRecursively( child,
depth + 1,
result );
}
} else if ( startAt instanceof Composite ) {
getContainedHierarchyRecursively( extractWidget( ((Composite) startAt) ),
depth + 1,
result );
}
}
private static class IndentedLineAccumulator {
final StringBuilder sb = new StringBuilder();
private void append( int depth, String s ) {
for ( int i = 0; i < depth; i++ ) {
sb.append(" ");
}
sb.append( s );
}
@Override
public String toString() {
return sb.toString();
}
}
private static native Widget extractWidget( Composite composite ) /*-{
return composite.@com.google.gwt.user.client.ui.Composite::widget;
}-*/;
/**
* Returns the current width or height of the given panel definition.
*
* @param position
* determines which dimension (width or height) to return.
* @param definition
* the definition to get the size information from.
* @return the with if position is EAST or WEST; the height if position is NORTH or SOUTH. May be null.
*/
public static Integer widthOrHeight( CompassPosition position, PanelDefinition definition ) {
switch ( position ) {
case NORTH:
case SOUTH:
return definition.getHeight();
case EAST:
case WEST:
return definition.getWidth();
default: throw new IllegalArgumentException( "Position " + position + " has no horizontal or vertial aspect." );
}
}
} |
package be.ibridge.kettle.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Properties;
import org.eclipse.core.runtime.IProgressMonitor;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Counter;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.DBCacheEntry;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_pun;
private PreparedStatement pstmt_dup;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private Row rowinfo;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch.
*/
private int batchCounter;
/**
* Construnct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
pstmt = null;
// rsmd = null;
rowinfo = null;
dbmd = null;
rowlimit=0;
written=0;
log.logDetailed(toString(), "New database connection defined");
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect()
throws KettleDatabaseException
{
try
{
if (databaseMeta!=null)
{
connect(databaseMeta.getDriverClass());
log.logDetailed(toString(), "Connected to database.");
}
else
{
throw new KettleDatabaseException("No valid database connection defined!");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connect(String classname)
throws KettleDatabaseException
{
// Install and load the jdbc Driver
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url = StringUtil.environmentSubstitute(databaseMeta.getURL());
String userName = StringUtil.environmentSubstitute(databaseMeta.getUsername());
String password = StringUtil.environmentSubstitute(databaseMeta.getPassword());
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(userName))
{
connection = DriverManager.getConnection(url, userName, password);
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(userName)) properties.put("user", userName);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public void disconnect()
{
try
{
if (connection==null) return ; // Nothing to do...
if (connection.isClosed()) return ; // Nothing to do...
if (!isAutoCommit()) commit();
if (pstmt !=null) { pstmt.close(); pstmt=null; }
if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; }
if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; }
if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; }
if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; }
if (connection !=null) { connection.close(); connection=null; }
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
}
}
public void cancelQuery() throws KettleDatabaseException
{
try
{
if (pstmt !=null)
{
pstmt.cancel();
}
if (sel_stmt !=null)
{
sel_stmt.cancel();
}
log.logDetailed(toString(), "Open query canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling query", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.rollback();
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param r The row to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(Row r, String table)
throws KettleDatabaseException
{
if (r.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(table, r);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(Row r)
throws KettleDatabaseException
{
setValues(r, pstmt);
}
public void setValuesInsert(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementInsert);
}
public void setValuesUpdate(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementUpdate);
}
public void setValuesLookup(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementLookup);
}
public void setProcValues(Row r, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
Value v=r.getValue(argnrs[i]);
setValue(cstmt, v, pos);
pos++;
}
}
}
public void setValue(PreparedStatement ps, Value v, int pos)
throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case Value.VALUE_TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull())
{
ps.setBigDecimal(pos, v.getBigNumber());
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case Value.VALUE_TYPE_NUMBER :
debug="Number";
if (!v.isNull())
{
double num = v.getNumber();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
num = Const.round(num, v.getPrecision());
}
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case Value.VALUE_TYPE_INTEGER:
debug="Integer";
if (!v.isNull())
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, Math.round( v.getNumber() ) );
}
else
{
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, v.getNumber() );
}
else
{
ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.BIGINT);
}
break;
case Value.VALUE_TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull() && v.getString()!=null)
{
ps.setString(pos, v.getString());
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull())
{
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = v.getStringLength();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = v.getString().substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case Value.VALUE_TYPE_DATE :
debug="Date";
if (!v.isNull() && v.getDate()!=null)
{
long dat = v.getDate().getTime();
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case Value.VALUE_TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull())
{
ps.setBoolean(pos, v.getBoolean());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull())
{
ps.setString(pos, v.getBoolean()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
// Sets the values of the preparedStatement pstmt.
public void setValues(Row r, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
//System.out.println("Setting value ["+v+"] on preparedStatement, position="+i);
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+r, e);
}
}
}
public void setDimValues(Row r, Value dateval)
throws KettleDatabaseException
{
setDimValues(r, dateval, prepStatementLookup);
}
// Sets the values of the preparedStatement pstmt.
public void setDimValues(Row r, Value dateval, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
long dat;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e);
}
}
if (dateval!=null && dateval.getDate()!=null && !dateval.isNull())
{
dat = dateval.getDate().getTime();
}
else
{
Calendar cal=Calendar.getInstance(); // use system date!
dat = cal.getTime().getTime();
}
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
try
{
ps.setTimestamp(r.size()+1, sdate); // ? > date_from
ps.setTimestamp(r.size()+2, sdate); // ? <= date_to
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex);
}
}
public void dimUpdate(Row row,
String table,
String fieldlookup[],
int fieldnrs[],
String returnkey,
Value dimkey
)
throws KettleDatabaseException
{
int i;
if (pstmt_dup==null) // first time: construct prepared statement
{
// Construct the SQL statement...
/*
* UPDATE d_customer
* SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
* ;
*/
String sql="UPDATE "+table+Const.CR+"SET ";
for (i=0;i<fieldlookup.length;i++)
{
if (i>0) sql+=", "; else sql+=" ";
sql+=fieldlookup[i]+" = ?"+Const.CR;
}
sql+="WHERE "+returnkey+" = ?";
try
{
log.logDebug(toString(), "Preparing statement: ["+sql+"]");
pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Coudln't prepare statement :"+Const.CR+sql, ex);
}
}
// Assemble information
// New
Row rupd=new Row();
for (i=0;i<fieldnrs.length;i++)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
rupd.addValue( dimkey );
setValues(rupd, pstmt_dup);
insertRow(pstmt_dup);
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
public void dimInsert(Row row,
String table,
boolean newentry,
String keyfield,
boolean autoinc,
Value technicalKey,
String versionfield,
Value val_version,
String datefrom,
Value val_datfrom,
String dateto,
Value val_datto,
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[])
* VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[])
* ;
*/
String sql="INSERT INTO "+databaseMeta.quoteField(table)+"( ";
if (!autoinc) sql+=databaseMeta.quoteField(keyfield)+", "; // NO AUTOINCREMENT
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix!
sql+=databaseMeta.quoteField(versionfield)+", "+databaseMeta.quoteField(datefrom)+", "+databaseMeta.quoteField(dateto);
for (i=0;i<keylookup.length;i++)
{
sql+=", "+databaseMeta.quoteField(keylookup[i]);
}
for (i=0;i<fieldlookup.length;i++)
{
sql+=", "+databaseMeta.quoteField(fieldlookup[i]);
}
sql+=") VALUES(";
if (!autoinc) sql+="?, ";
sql+="?, ?, ?";
for (i=0;i<keynrs.length;i++)
{
sql+=", ?";
}
for (i=0;i<fieldnrs.length;i++)
{
sql+=", ?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
//pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex);
}
/*
* UPDATE d_customer
* SET dateto = val_datnow
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
String sql_upd="UPDATE "+databaseMeta.quoteField(table)+Const.CR+"SET "+databaseMeta.quoteField(dateto)+" = ?"+Const.CR;
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=databaseMeta.quoteField(keylookup[i])+" = ?"+Const.CR;
}
sql_upd+="AND "+databaseMeta.quoteField(versionfield)+" = ? ";
try
{
log.logDetailed(toString(), "Preparing update: "+Const.CR+sql_upd+Const.CR);
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql_upd, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(technicalKey);
if (!newentry)
{
Value val_new_version = new Value(val_version);
val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version
rins.addValue(val_new_version);
}
else
{
rins.addValue(val_version);
}
rins.addValue(val_datfrom);
rins.addValue(val_datto);
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
for (i=0;i<fieldnrs.length;i++)
{
Value val = row.getValue(fieldnrs[i]);
rins.addValue( val );
}
log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
log.logDebug(toString(), "Row inserted!");
if (keyfield==null)
{
try
{
Row keys = getGeneratedKeys(prepStatementInsert);
if (keys.size()>0)
{
technicalKey.setValue(keys.getValue(0).getInteger());
}
else
{
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : no value found!");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : unexpected error: ", e);
}
}
if (!newentry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer
* SET dateto = val_datfrom
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
Row rupd = new Row();
rupd.addValue(val_datfrom);
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
rupd.addValue(val_version);
log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString());
// UPDATE VALUES
setValues(rupd, prepStatementUpdate); // set values for update
log.logDebug(toString(), "Values set for update ("+rupd.size()+")");
insertRow(prepStatementUpdate); // do the actual update
log.logDebug(toString(), "Row updated!");
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public Row getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
Row rowInfo = getRowInfo(resultSetMetaData);
return getRow(keys, resultSetMetaData, rowInfo);
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
// This updates all versions of a dimension entry.
public void dimPunchThrough(Row row,
String table,
int fieldupdate[],
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
boolean first;
if (pstmt_pun==null) // first time: construct prepared statement
{
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+table+Const.CR;
sql_upd+="SET ";
first=true;
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=fieldlookup[i]+" = ?"+Const.CR;
}
}
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
try
{
pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Row rupd=new Row();
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
}
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
// UPDATE VALUES
setValues(rupd, pstmt_pun); // set values for update
insertRow(pstmt_pun); // do the actual update
}
/**
* This inserts new record into a junk dimension
*/
public void combiInsert( Row row,
String table,
String keyfield,
boolean autoinc,
Value val_key,
String keylookup[],
int keynrs[],
boolean crc,
String crcfield,
Value val_crc
)
throws KettleDatabaseException
{
String debug="Combination insert";
try
{
boolean comma;
if (prepStatementInsert==null) // first time: construct prepared statement
{
debug="First: construct prepared statement";
/* Construct the SQL statement...
*
* INSERT INTO
* d_test(keyfield, [crcfield,] keylookup[])
* VALUES(val_key, [val_crc], row values with keynrs[])
* ;
*/
StringBuffer sql = new StringBuffer(100);
sql.append("INSERT INTO ").append(databaseMeta.quoteField(table)).append("( ");
comma=false;
if (!autoinc) // NO AUTOINCREMENT
{
sql.append(databaseMeta.quoteField(keyfield));
comma=true;
}
else
if (databaseMeta.needsPlaceHolder())
{
sql.append('0'); // placeholder on informix! Will be replaced in table by real autoinc value.
comma=true;
}
if (crc)
{
if (comma) sql.append(", ");
sql.append(databaseMeta.quoteField(crcfield));
comma=true;
}
for (int i=0;i<keylookup.length;i++)
{
if (comma) sql.append(", ");
sql.append(databaseMeta.quoteField(keylookup[i]));
comma=true;
}
sql.append(") VALUES (");
comma=false;
if (keyfield!=null)
{
sql.append('?');
comma=true;
}
if (crc)
{
if (comma) sql.append(',');
sql.append('?');
comma=true;
}
for (int i=0;i<keylookup.length;i++)
{
if (comma) sql.append(','); else comma=true;
sql.append('?');
}
sql.append(" )");
String sqlStatement = sql.toString();
try
{
debug="First: prepare statement";
if (keyfield==null)
{
log.logDetailed(toString(), "SQL with return keys: "+sqlStatement);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL without return keys: "+sqlStatement);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex);
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex);
}
}
debug="Create new insert row rins";
Row rins=new Row();
if (!autoinc) rins.addValue(val_key);
if (crc)
{
rins.addValue(val_crc);
}
for (int i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
if (log.isRowLevel()) log.logRowlevel(toString(), "rins="+rins.toString());
debug="Set values on insert";
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
debug="Insert row";
insertRow(prepStatementInsert);
debug="Retrieve key";
if (keyfield==null)
{
ResultSet keys = null;
try
{
keys=prepStatementInsert.getGeneratedKeys(); // 1 key
if (keys.next()) val_key.setValue(keys.getDouble(1));
else
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset");
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex);
}
finally
{
try
{
if ( keys != null ) keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex);
}
}
}
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unexpected error in combination insert in part ["+debug+"] : "+e.toString(), e);
}
}
public Value getNextSequenceValue(String seq, String keyfield)
throws KettleDatabaseException
{
Value retval=null;
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
long next = rs.getLong(1);
retval=new Value(keyfield, next);
retval.setLength(9,0);
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex);
}
return retval;
}
public void insertRow(String tableName, Row fields)
throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, Row fields)
{
StringBuffer ins=new StringBuffer(128);
ins.append("INSERT INTO ").append(databaseMeta.quoteField(tableName)).append("(");
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValue(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(")");
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounter The batchCounter to set.
*/
public void setBatchCounter(int batchCounter)
{
this.batchCounter = batchCounter;
}
/**
* @return Returns the batchCounter.
*/
public int getBatchCounter()
{
return batchCounter;
}
private long testCounter = 0;
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commitsize)
* @throws KettleDatabaseException
*/
public void insertRow(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
String debug="insertRow start";
try
{
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates();
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
batchCounter++;
ps.addBatch(); // Add the batch, but don't forget to run the batch
testCounter++;
// System.out.println("testCounter is at "+testCounter);
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
// System.out.println("EXECUTE BATCH, testcounter is at "+testCounter);
batchCounter=0;
}
else
{
debug="insertRow normal commit";
commit();
}
}
}
catch(BatchUpdateException ex)
{
//System.out.println("Batch update exception "+ex.getMessage());
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
throw kdbe;
}
catch(SQLException ex)
{
log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
public void insertFinished(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
//System.out.println("Executing batch with "+batchCounter+" elements...");
ps.executeBatch();
commit();
}
else
{
commit();
}
}
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null);
}
public Result execStatement(String sql, Row params) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE"))
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script)
throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Row r = getRow(rs);
while (r!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
log.logDetailed(toString(), r.toString());
r=getRow(rs);
}
}
else
{
log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql)
throws KettleDatabaseException
{
return openQuery(sql, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, Row params) throws KettleDatabaseException
{
return openQuery(sql, params, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, Row params, int fetch_mode) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowinfo = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL);
}
catch(SQLException ex)
{
log.logError(toString(), "ERROR executing ["+sql+"]");
log.logError(toString(), "ERROR in part: ["+debug+"]");
printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() && ( statement.getMaxRows()>0 || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL);
}
public ResultSet openQuery(PreparedStatement ps, Row params)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
rowinfo = getRowInfo(res.getMetaData());
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public Row getTableFields(String tablename)
throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public Row getQueryFields(String sql, boolean param)
throws KettleDatabaseException
{
return getQueryFields(sql, param, null);
}
/**
* See if the table specified exists by looking at the data dictionary!
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename)
throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName)
throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(sequenceName);
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tablename, String idx_fields[])
throws KettleDatabaseException
{
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
// Get the info from the data dictionary...
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
// Get the info from the data dictionary...
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
e.printStackTrace();
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON "+databaseMeta.quoteField(tablename)+Const.CR;
cr_index += "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
String cr_seq="";
if (sequence==null || sequence.length()==0) return cr_seq;
if (databaseMeta.supportsSequences())
{
cr_seq += "CREATE SEQUENCE "+databaseMeta.quoteField(sequence)+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public Row getQueryFields(String sql, boolean param, Row inform) throws KettleDatabaseException
{
Row fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
String debug="";
try
{
if (inform==null)
{
debug="inform==null";
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug="isFetchSizeSupported()";
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
debug = "Set fetchsize";
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
debug = "Set max rows to 1";
sel_stmt.setMaxRows(1);
debug = "exec query";
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
debug = "getQueryFields get row info";
fields = getRowInfo(r.getMetaData());
debug="close resultset";
r.close();
debug="close statement";
sel_stmt.close();
sel_stmt=null;
}
else
{
debug="prepareStatement";
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
Row par = inform;
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(ps);
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(sql, inform);
setValues(par, ps);
}
debug="executeQuery()";
ResultSet r = ps.executeQuery();
debug="getRowInfo";
fields=getRowInfo(ps.getMetaData());
debug="close resultset";
r.close();
debug="close preparedStatement";
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e);
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
public void closeQuery(ResultSet res)
throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
private Row getRowInfo(ResultSetMetaData rm) throws KettleDatabaseException
{
return getRowInfo(rm, false);
}
// Build the row using ResultSetMetaData rsmd
private Row getRowInfo(ResultSetMetaData rm, boolean ignoreLength) throws KettleDatabaseException
{
int nrcols;
int i;
Value v;
String name;
int type, valtype;
int precision;
int length;
if (rm==null) return null;
rowinfo = new Row();
try
{
nrcols=rm.getColumnCount();
for (i=1;i<=nrcols;i++)
{
name=new String(rm.getColumnName(i));
type=rm.getColumnType(i);
valtype=Value.VALUE_TYPE_NONE;
length=-1;
precision=-1;
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=Value.VALUE_TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(i);
// System.out.println("Display of "+name+" = "+precision);
// System.out.println("Precision of "+name+" = "+rm.getPrecision(i));
// System.out.println("Scale of "+name+" = "+rm.getScale(i));
break;
case java.sql.Types.CLOB:
valtype=Value.VALUE_TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
break;
case java.sql.Types.BIGINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=Value.VALUE_TYPE_NUMBER;
length=rm.getPrecision(i);
precision=rm.getScale(i);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If were dealing with Postgres and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=Value.VALUE_TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision<=0 && length<=0) // undefined size: BIGNUMBER
{
valtype=Value.VALUE_TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=Value.VALUE_TYPE_DATE;
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=Value.VALUE_TYPE_BOOLEAN;
break;
default:
valtype=Value.VALUE_TYPE_STRING;
length=rm.getPrecision(i);
precision=rm.getScale(i);
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2)
{
if (type == java.sql.Types.BINARY && ((2 * length) == rm.getColumnDisplaySize(i)))
{
// Patch for DB2 "CHAR FOR BITDATA". E.g. when getPrecision() is 10,
// the display size is 20.
length = rm.getColumnDisplaySize(i);
}
}
break;
}
// TODO: grab the comment as a description to the field, later
// comment=rm.getColumnLabel(i);
v=new Value(name, valtype);
v.setLength(length, precision);
rowinfo.addValue(v);
}
return rowinfo;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
// Build the row using ResultSetMetaData rsmd
/*
private Row getRowInfo() throws KettleDatabaseException
{
return getRowInfo(rsmd);
}
*/
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Row getRow(ResultSet rs) throws KettleDatabaseException
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
if (rowinfo==null)
{
rowinfo = getRowInfo(rsmd);
}
return getRow(rs, rsmd, rowinfo);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Row getRow(ResultSet rs, ResultSetMetaData resultSetMetaData, Row rowInfo)
throws KettleDatabaseException
{
Row row;
int nrcols, i;
Value val;
try
{
nrcols=resultSetMetaData.getColumnCount();
if (rs.next())
{
row=new Row();
for (i=0;i<nrcols;i++)
{
val=new Value(rowInfo.getValue(i)); // copy info from meta-data.
switch(val.getType())
{
case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break;
case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break;
case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break;
case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break;
case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break;
case Value.VALUE_TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
val.setValue( rs.getTimestamp(i+1) ); break;
}
else
{
val.setValue( rs.getDate(i+1) ); break;
}
default: break;
}
if (rs.wasNull()) val.setNull(); // null value!
row.addValue(val);
}
}
else
{
row=null;
}
return row;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
// Lookup certain fields in a table
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+databaseMeta.quoteField(table)+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults)
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
// Lookup certain fields in a table
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
int i;
sql.append("UPDATE ").append(databaseMeta.quoteField(table)).append(Const.CR).append("SET ");
for (i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(" ").append(condition[i]).append(" ");
}
else
{
sql.append(" ").append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
String sql;
int i;
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
int i;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
/*
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
* datefield: do we have a datefield?
* datefrom, dateto: date-range, if any.
*/
public boolean setDimLookup(String table,
String keys[],
String tk,
String version,
String extra[],
String extraRename[],
String datefrom,
String dateto
)
throws KettleDatabaseException
{
String sql;
int i;
/*
* SELECT <tk>, <version>, ...
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefield> BETWEEN <datefrom> AND <dateto>
* ;
*
*/
sql = "SELECT "+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version);
if (extra!=null)
{
for (i=0;i<extra.length;i++)
{
if (extra[i]!=null && extra[i].length()!=0)
{
sql+=", "+databaseMeta.quoteField(extra[i]);
if (extraRename[i]!=null &&
extraRename[i].length()>0 &&
!extra[i].equals(extraRename[i]))
{
sql+=" AS "+databaseMeta.quoteField(extraRename[i]);
}
}
}
}
sql+= " FROM "+databaseMeta.quoteField(table)+" WHERE ";
for (i=0;i<keys.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(keys[i])+" = ? ";
}
sql += " AND ? >= "+databaseMeta.quoteField(datefrom)+" AND ? < "+databaseMeta.quoteField(dateto);
try
{
log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
prepStatementLookup.setFetchSize(0); // Make sure to DISABLE Streaming Result sets
}
log.logDetailed(toString(), "Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
return true;
}
/* CombinationLookup
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
*/
public void setCombiLookup(String table,
String keys[],
String retval,
boolean crc,
String crcfield
)
throws KettleDatabaseException
{
StringBuffer sql = new StringBuffer(100);
int i;
boolean comma;
/*
* SELECT <retval>
* FROM <table>
* WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
* OR
*
* SELECT <retval>
* FROM <table>
* WHERE <crcfield> = ?
* AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
*/
sql.append("SELECT ").append(databaseMeta.quoteField(retval)).append(Const.CR);
sql.append("FROM ").append(databaseMeta.quoteField(table)).append(Const.CR);
sql.append("WHERE ");
comma=false;
if (crc)
{
sql.append(databaseMeta.quoteField(crcfield)).append(" = ? ").append(Const.CR);
comma=true;
}
else
{
sql.append("( ( ");
}
for (i=0;i<keys.length;i++)
{
if (comma)
{
sql.append(" AND ( ( ");
}
else
{
comma=true;
}
sql.append(databaseMeta.quoteField(keys[i])).append(" = ? ) OR ( ").append(databaseMeta.quoteField(keys[i]));
sql.append(" IS NULL AND ");
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_DB2)
{
sql.append("CAST(? AS VARCHAR(256)) IS NULL");
}
else
{
sql.append("? IS NULL");
}
sql.append(" ) )");
sql.append(Const.CR);
}
try
{
String sqlStatement = sql.toString();
log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sqlStatement);
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sqlStatement));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex);
}
}
public Row callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype)
throws KettleDatabaseException
{
Row ret;
try
{
cstmt.execute();
ret=new Row();
int pos=1;
if (resultname!=null && resultname.length()!=0)
{
Value v=new Value(resultname, Value.VALUE_TYPE_NONE);
switch(resulttype)
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break;
}
ret.addValue(v);
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
Value v=new Value(arg[i], Value.VALUE_TYPE_NONE);
switch(argtype[i])
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break;
}
ret.addValue(v);
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
public Row getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Row getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Row getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Row getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
String debug = "start";
Row ret;
ResultSet res = null;
try
{
debug = "pstmt.executeQuery()";
res = ps.executeQuery();
debug = "getRowInfo()";
rowinfo = getRowInfo(res.getMetaData());
debug = "getRow(res)";
ret=getRow(res);
if (failOnMultipleResults)
{
if (res.next())
{
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
debug = "res.close()";
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
finally
{
try
{
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData()
throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, Row fields)
throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk)
throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
if (checkTableExists(tablename))
{
retval=getAlterTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
return retval;
}
public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+databaseMeta.quoteField(tablename)+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
Value v=fields.getValue(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval="";
String tableName = databaseMeta.quoteField(tablename);
// Get the fields that are in the table now:
Row tabFields = getTableFields(tablename);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
Row missing = new Row();
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
// Not found?
if (tabFields.searchValue( v.getName() )==null )
{
missing.addValue(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
Value v=missing.getValue(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
Row surplus = new Row();
for (int i=0;i<tabFields.size();i++)
{
Value v = tabFields.getValue(i);
// Found in table, not in input ?
if (fields.searchValue( v.getName() )==null )
{
surplus.addValue(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
Value v=surplus.getValue(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for wich we need to modify the type... (length, precision)
Row modify = new Row();
for (int i=0;i<fields.size();i++)
{
Value desiredField = fields.getValue(i);
Value currentField = tabFields.searchValue( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValue(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
Value v=modify.getValue(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc)
throws KettleDatabaseException
{
int start_tk = databaseMeta.getNotFoundTK(use_autoinc);
String sql = "SELECT count(*) FROM "+databaseMeta.quoteField(tablename)+" WHERE "+databaseMeta.quoteField(tk)+" = "+start_tk;
Row r = getOneRow(sql);
Value count = r.getValue(0);
if (count.getNumber() == 0)
{
try
{
Statement st = connection.createStatement();
String isql;
if (!databaseMeta.supportsAutoinc() || !use_autoinc)
{
isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)";
}
else
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_CACHE :
case DatabaseMeta.TYPE_DATABASE_GUPTA :
case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_INFORMIX :
case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (1, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_MSSQL :
case DatabaseMeta.TYPE_DATABASE_DB2 :
case DatabaseMeta.TYPE_DATABASE_DBASE :
case DatabaseMeta.TYPE_DATABASE_GENERIC :
case DatabaseMeta.TYPE_DATABASE_SYBASE :
case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(version)+") values (1)"; break;
default: isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break;
}
}
st.executeUpdate(databaseMeta.stripCR(isql));
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e);
}
}
}
public Value checkSequence(String seqname)
throws KettleDatabaseException
{
String sql=null;
if (databaseMeta.supportsSequences())
{
sql = databaseMeta.getSQLCurrentSequenceValue(seqname);
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
if (r!=null)
{
Value last = r.getValue(0);
// errorstr="Sequence is at number: "+last.toString();
return last;
}
else
{
return null;
}
}
else
{
throw new KettleDatabaseException("Sequences are only available for Oracle databases.");
}
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
execStatement(databaseMeta.getTruncateTableStatement(tablename));
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public Row getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, null);
if (rs!=null)
{
Row r = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public Row getOneRow(String sql, Row param)
throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param);
if (rs!=null)
{
Row r = getRow(rs); // One value: a number;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
rowinfo=null;
return r;
}
else
{
return null;
}
}
public Row getParameterMetaData(PreparedStatement ps)
{
Row par = new Row();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
Value val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new Value(name, Value.VALUE_TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new Value(name, Value.VALUE_TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new Value(name, Value.VALUE_TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new Value(name, Value.VALUE_TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new Value(name, Value.VALUE_TYPE_BOOLEAN);
break;
default:
val=new Value(name, Value.VALUE_TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new Value(name, Value.VALUE_TYPE_BIGNUMBER);
}
val.setNull();
par.addValue(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public Row getParameterMetaData(String sql, Row inform)
{
// The database coudln't handle it: try manually!
int q=countParameters(sql);
Row par=new Row();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
Value inf=inform.getValue(i);
Value v = new Value(inf);
par.addValue(v);
}
}
else
{
for (int i=0;i<q;i++)
{
Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER);
v.setValue( 0.0 );
par.addValue(v);
}
}
return par;
}
public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_batchid)
{
v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v);
}
v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_jobid)
{
v=new Value("ID_JOB", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
}
v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
java.util.Date replayDate,
String log_string
)
throws KettleDatabaseException
{
if (use_id && log_string!=null && !status.equalsIgnoreCase("start"))
{
String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," +
" LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " +
"WHERE ";
if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?";
Row r = new Row();
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
r.addValue( new Value("REPLAYDATE", replayDate ));
Value logfield = new Value("LOG_FIELD", log_string);
logfield.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( logfield );
r.addValue( new Value("ID_BATCH", id ));
execStatement(sql, r);
}
else
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=14;
}
else
{
sql+="JOBNAME";
parms=13;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=14;
}
else
{
sql+="TRANSNAME";
parms=13;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
if (job)
{
if (use_id)
{
r.addValue( new Value("ID_BATCH", id ));
}
r.addValue( new Value("TRANSNAME", name ));
}
else
{
if (use_id)
{
r.addValue( new Value("ID_JOB", id ));
}
r.addValue( new Value("JOBNAME", name ));
}
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
r.addValue( new Value("REPLAYDATE", replayDate ));
if (log_string!=null && log_string.length()>0)
{
Value large = new Value("LOG_FIELD", log_string );
large.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( large );
}
setValues(r);
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
}
public Row getLastLogDate( String logtable,
String name,
boolean job,
String status
)
throws KettleDatabaseException
{
Row row=null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
r.addValue( new Value("TRANSNAME", name ));
setValues(r);
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowinfo = getRowInfo(res.getMetaData());
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized void getNextValue(Hashtable counters, String table, Value val_key)
throws KettleDatabaseException
{
String lookup = databaseMeta.quoteField(table)+"."+databaseMeta.quoteField(val_key.getName());
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=(Counter)counters.get(lookup);
if (counter==null)
{
Row r = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key.getName())+") FROM "+databaseMeta.quoteField(table));
if (r!=null)
{
counter = new Counter(r.getValue(0).getInteger()+1, 1);
val_key.setValue(counter.next());
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+table);
}
}
else
{
val_key.setValue(counter.next());
}
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
try
{
ArrayList result = new ArrayList();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Row row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
String sql = "SELECT * FROM "+databaseMeta.quoteField(table_name);
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public Row getReturnRow()
{
return rowinfo;
}
public String[] getTableTypes()
throws KettleDatabaseException
{
try
{
ArrayList types = new ArrayList();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return (String[])types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames()
throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got table from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getViews()
throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
ArrayList procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Row)procs.get(i)).getValue(0).getString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
ArrayList rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Row row = (Row)rows.get(i);
String procCatalog = row.getString("PROCEDURE_CAT", null);
String procSchema = row.getString("PROCEDURE_SCHEMA", null);
String procName = row.getString("PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLLockTables(tableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLUnlockTables(tableNames);
if (sql!=null)
{
execStatement(sql);
}
}
} |
package datamanagement;
import javax.swing.JLabel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JFrame;
import javax.swing.DefaultComboBoxModel;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class CheckGradeUserInterface extends JFrame
implements IUnitLister, IStudentLister
{
// Variables
private CheckGradeController controller_;
private DefaultComboBoxModel unitComboBoxModel_; // Parameterize model to <String>?
private DefaultComboBoxModel studentComboBoxModel_;
private float assessmentOneMark_;
private float assessmentTwoMark_;
private float examMark_;
private Integer studentId_;
// Constructors
public CheckGradeUserInterface(CheckGradeController ctl)
{
this.controller_ = ctl;
unitComboBoxModel_ = new DefaultComboBoxModel(new String[0]);
studentComboBoxModel_ = new DefaultComboBoxModel(new String[0]);
initComponents();
selectUnitComboBox.setModel(unitComboBoxModel_);
selectStudentComboBox.setModel(studentComboBoxModel_);
errorMessageLabel.setText("");
}
// Methods
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
// desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
checkGradeTitleLabel = new javax.swing.JLabel();
unitSelectionPanel = new javax.swing.JPanel();
selectUnitComboBox = new javax.swing.JComboBox();
studentSelectionPanel = new javax.swing.JPanel();
selectStudentComboBox = new javax.swing.JComboBox();
markDisplayPanel = new javax.swing.JPanel();
assessmentOneLabel = new javax.swing.JLabel();
assessmentTwoLabel = new javax.swing.JLabel();
examLabel = new javax.swing.JLabel();
assessementOneMarkTextField = new javax.swing.JTextField();
assessmentTwoMarkTestField = new javax.swing.JTextField();
examMarkTextField = new javax.swing.JTextField();
changeButton = new javax.swing.JButton();
gradeDisplayPanel = new javax.swing.JPanel();
gradeDisplayLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
checkGradeTitleLabel.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
checkGradeTitleLabel.setText("Check Grade UI");
unitSelectionPanel
.setBorder(javax.swing.BorderFactory.createTitledBorder("Unit"));
selectUnitComboBox.setModel(unitComboBoxModel_);
selectUnitComboBox.addItemListener(new java.awt.event.ItemListener()
{
public void itemStateChanged(java.awt.event.ItemEvent evt)
{
jComboBox1ItemStateChanged(evt);
}
});
javax.swing.GroupLayout gl_unitSelectionPanel = new javax.swing.GroupLayout(
unitSelectionPanel);
unitSelectionPanel.setLayout(gl_unitSelectionPanel);
gl_unitSelectionPanel.setHorizontalGroup(gl_unitSelectionPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(gl_unitSelectionPanel.createSequentialGroup()
.addContainerGap()
.addComponent(selectUnitComboBox,
javax.swing.GroupLayout.PREFERRED_SIZE, 185,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
gl_unitSelectionPanel.setVerticalGroup(gl_unitSelectionPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(gl_unitSelectionPanel.createSequentialGroup()
.addComponent(selectUnitComboBox,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
studentSelectionPanel
.setBorder(javax.swing.BorderFactory.createTitledBorder("Student"));
selectStudentComboBox.setModel(studentComboBoxModel_);
selectStudentComboBox.addItemListener(new java.awt.event.ItemListener()
{
public void itemStateChanged(java.awt.event.ItemEvent evt)
{
jComboBox2ItemStateChanged(evt);
}
});
javax.swing.GroupLayout gl_studentSelectionPanel = new javax.swing.GroupLayout(
studentSelectionPanel);
studentSelectionPanel.setLayout(gl_studentSelectionPanel);
gl_studentSelectionPanel.setHorizontalGroup(gl_studentSelectionPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(gl_studentSelectionPanel.createSequentialGroup()
.addContainerGap()
.addComponent(selectStudentComboBox,
javax.swing.GroupLayout.PREFERRED_SIZE, 185,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
gl_studentSelectionPanel.setVerticalGroup(gl_studentSelectionPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(gl_studentSelectionPanel.createSequentialGroup()
.addComponent(selectStudentComboBox,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
markDisplayPanel
.setBorder(javax.swing.BorderFactory.createTitledBorder("Marks"));
assessmentOneLabel.setText("Asg1:");
assessmentTwoLabel.setText("Asg2:");
examLabel.setText("Exam:");
assessementOneMarkTextField.setEditable(false);
assessementOneMarkTextField.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
jTextFieldKeyTyped(evt);
}
});
assessmentTwoMarkTestField.setEditable(false);
assessmentTwoMarkTestField.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
jTextFieldKeyTyped(evt);
}
});
examMarkTextField.setEditable(false);
examMarkTextField.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyTyped(java.awt.event.KeyEvent evt)
{
jTextFieldKeyTyped(evt);
}
});
changeButton.setText("Change");
changeButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
checkGradeButton = new javax.swing.JButton();
checkGradeButton.setText("Check Grade");
checkGradeButton.setActionCommand("checkGrade");
checkGradeButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout gl_markDisplayPanel = new javax.swing.GroupLayout(
markDisplayPanel);
gl_markDisplayPanel.setHorizontalGroup(gl_markDisplayPanel
.createParallelGroup(Alignment.LEADING)
.addGroup(gl_markDisplayPanel.createSequentialGroup()
.addGroup(gl_markDisplayPanel
.createParallelGroup(Alignment.LEADING)
.addGroup(gl_markDisplayPanel
.createSequentialGroup().addContainerGap()
.addComponent(assessmentOneLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(assessementOneMarkTextField,
GroupLayout.PREFERRED_SIZE, 59,
GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(assessmentTwoLabel))
.addGroup(gl_markDisplayPanel
.createSequentialGroup().addGap(85)
.addComponent(changeButton,
GroupLayout.PREFERRED_SIZE, 84,
GroupLayout.PREFERRED_SIZE)))
.addGap(18)
.addGroup(gl_markDisplayPanel
.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_markDisplayPanel
.createSequentialGroup()
.addComponent(assessmentTwoMarkTestField,
GroupLayout.PREFERRED_SIZE, 59,
GroupLayout.PREFERRED_SIZE)
.addGap(18).addComponent(examLabel))
.addComponent(checkGradeButton))
.addGap(18)
.addComponent(examMarkTextField, GroupLayout.PREFERRED_SIZE,
59, GroupLayout.PREFERRED_SIZE)
.addGap(15)));
gl_markDisplayPanel.setVerticalGroup(
gl_markDisplayPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_markDisplayPanel.createSequentialGroup()
.addGroup(gl_markDisplayPanel
.createParallelGroup(Alignment.BASELINE)
.addComponent(assessmentOneLabel)
.addComponent(assessementOneMarkTextField,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(assessmentTwoLabel)
.addComponent(assessmentTwoMarkTestField,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(examLabel)
.addComponent(examMarkTextField,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_markDisplayPanel
.createParallelGroup(Alignment.BASELINE)
.addComponent(changeButton)
.addComponent(checkGradeButton))
.addContainerGap()));
markDisplayPanel.setLayout(gl_markDisplayPanel);
gradeDisplayPanel
.setBorder(javax.swing.BorderFactory.createTitledBorder("Grade"));
gradeDisplayLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
gradeDisplayLabel.setForeground(new java.awt.Color(255, 0, 0));
gradeDisplayLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
gradeDisplayLabel.setText("grade");
javax.swing.GroupLayout gl_gradeDisplayPanel = new javax.swing.GroupLayout(
gradeDisplayPanel);
gradeDisplayPanel.setLayout(gl_gradeDisplayPanel);
gl_gradeDisplayPanel.setHorizontalGroup(gl_gradeDisplayPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gradeDisplayLabel,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 153,
Short.MAX_VALUE));
gl_gradeDisplayPanel.setVerticalGroup(gl_gradeDisplayPanel
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(gl_gradeDisplayPanel.createSequentialGroup()
.addGap(34, 34, 34).addComponent(gradeDisplayLabel)
.addContainerGap(43, Short.MAX_VALUE)));
errorMessageLabel = new JLabel();
errorMessageLabel.setText("Error message");
errorMessageLabel.setForeground(Color.RED);
errorMessageLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
saveButton = new javax.swing.JButton();
saveButton.setText("Save");
saveButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGroup(layout
.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addContainerGap()
.addComponent(errorMessageLabel,
GroupLayout.DEFAULT_SIZE, 400,
Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup().addContainerGap()
.addGroup(layout
.createParallelGroup(Alignment.LEADING,
false)
.addComponent(markDisplayPanel,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout
.createParallelGroup(
Alignment.LEADING)
.addComponent(
unitSelectionPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(
studentSelectionPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addComponent(gradeDisplayPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup().addGap(157)
.addComponent(checkGradeTitleLabel))
.addGroup(layout.createSequentialGroup().addGap(165)
.addComponent(saveButton,
GroupLayout.PREFERRED_SIZE, 86,
GroupLayout.PREFERRED_SIZE)))
.addContainerGap()));
layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addContainerGap()
.addComponent(checkGradeTitleLabel).addGap(13)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(unitSelectionPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(studentSelectionPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addComponent(gradeDisplayPanel,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(markDisplayPanel, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(saveButton).addGap(11)
.addComponent(errorMessageLabel, GroupLayout.PREFERRED_SIZE,
30, GroupLayout.PREFERRED_SIZE)
.addContainerGap()));
getContentPane().setLayout(layout);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt)
{// GEN-FIRST:event_jComboBox1ItemStateChanged
String cU = (String) selectUnitComboBox.getSelectedItem();
Refresh3();
clearStudents();
if (evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
if (cU.equals((String) selectUnitComboBox.getItemAt(0))) {
cU = "NONE";
}
controller_.unitSelected(cU);
}
}// GEN-LAST:event_jComboBox1ItemStateChanged
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt)
{// GEN-FIRST:event_jComboBox2ItemStateChanged
Refresh3();
String cS = (String) selectStudentComboBox.getSelectedItem();
if (evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
if (cS.equals((String) selectStudentComboBox.getItemAt(0))) {
studentId_ = new Integer(0);
controller_.studentSelected(studentId_);
}
else {
studentId_ = new Integer(cS.split("\\s")[0]);
}
controller_.studentSelected(studentId_);
}
}// GEN-LAST:event_jComboBox2ItemStateChanged
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{// GEN-FIRST:event_jButton3ActionPerformed
assessmentOneMark_ = new Float(assessementOneMarkTextField.getText()).floatValue();
assessmentTwoMark_ = new Float(assessmentTwoMarkTestField.getText()).floatValue();
examMark_ = new Float(examMarkTextField.getText()).floatValue();
// lblErrMsg.setText("");
try {
String s = controller_.checkGrade(assessmentOneMark_, assessmentTwoMark_, examMark_);
gradeDisplayLabel.setText(s);
}
catch (RuntimeException re) {
errorMessageLabel.setText(re.getMessage());
}
}// GEN-LAST:event_jButton3ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{// GEN-FIRST:event_jButton1ActionPerformed
controller_.enableChangeMarks();
gradeDisplayLabel.setText("");
// lblErrMsg.setText("");
}// GEN-LAST:event_jButton1ActionPerformed
private void jTextFieldKeyTyped(java.awt.event.KeyEvent evt)
{// GEN-FIRST:event_jTextField1KeyTyped
gradeDisplayLabel.setText("");
errorMessageLabel.setText("");
}// GEN-LAST:event_jTextField1KeyTyped
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{// GEN-FIRST:event_jButton2ActionPerformed
float asg1 = new Float(assessementOneMarkTextField.getText()).floatValue();
float asg2 = new Float(assessmentTwoMarkTestField.getText()).floatValue();
float exam = new Float(examMarkTextField.getText()).floatValue();
errorMessageLabel.setText("");
try {
controller_.saveGrade(asg1, asg2, exam);
// jButton3ActionPerformed(null);
}
catch (RuntimeException re) {
errorMessageLabel.setText(re.getMessage());
}
}// GEN-LAST:event_jButton2ActionPerformed
public void clearUnits()
{
unitComboBoxModel_.removeAllElements();
unitComboBoxModel_.addElement("<none selected>");
clearStudents();
}
public void addUnit(IUnit u)
{
unitComboBoxModel_.addElement(u.getUnitCode());
}
public void setState1(boolean b)
{
selectUnitComboBox.setEnabled(b);
errorMessageLabel.setText("");
}
public void clearStudents()
{
studentComboBoxModel_.removeAllElements();
studentComboBoxModel_.addElement("<none selected>");
}
public void addStudent(IStudent student)
{
studentComboBoxModel_.addElement(student.getID().toString() + " : " + student.getFirstName()
+ " " + student.getLastName());
}
public void setState2(boolean b)
{
selectStudentComboBox.setEnabled(b);
errorMessageLabel.setText("");
}
public void setRecord(IStudentUnitRecord record)
{
assessementOneMarkTextField.setText(new Float(record.getAssessmentOneMark()).toString());
assessmentTwoMarkTestField.setText(new Float(record.getAssessmentTwoMark()).toString());
examMarkTextField.setText(new Float(record.getExamMark()).toString());
gradeDisplayLabel.setText("");
}
public void Refresh3()
{
assessementOneMarkTextField.setText("");
assessmentTwoMarkTestField.setText("");
examMarkTextField.setText("");
gradeDisplayLabel.setText("");
errorMessageLabel.setText("");
assessementOneMarkTextField.setEditable(false);
assessmentTwoMarkTestField.setEditable(false);
examMarkTextField.setEditable(false);
}
public void setState3(boolean b)
{
checkGradeButton.setEnabled(b);
}
public void setState4(boolean b)
{
changeButton.setEnabled(b);
// gradeLB.setText("");
}
public void setState5(boolean b)
{
assessementOneMarkTextField.setEditable(b);
assessmentTwoMarkTestField.setEditable(b);
examMarkTextField.setEditable(b);
}
public void setState6(boolean b)
{
saveButton.setEnabled(b);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton changeButton;
private javax.swing.JButton checkGradeButton;
private javax.swing.JButton saveButton;
private javax.swing.JComboBox selectUnitComboBox;
private javax.swing.JComboBox selectStudentComboBox;
private javax.swing.JLabel checkGradeTitleLabel;
private javax.swing.JLabel assessmentOneLabel;
private javax.swing.JLabel assessmentTwoLabel;
private javax.swing.JLabel examLabel;
private javax.swing.JLabel gradeDisplayLabel;
private javax.swing.JLabel errorMessageLabel;
private javax.swing.JPanel unitSelectionPanel;
private javax.swing.JPanel studentSelectionPanel;
private javax.swing.JPanel markDisplayPanel;
private javax.swing.JPanel gradeDisplayPanel;
private javax.swing.JTextField assessementOneMarkTextField;
private javax.swing.JTextField assessmentTwoMarkTestField;
private javax.swing.JTextField examMarkTextField;
} |
package org.devgateway.ocds.web.rest.controller.selector;
import io.swagger.annotations.ApiOperation;
import org.devgateway.ocds.persistence.mongo.Organization;
import org.devgateway.ocds.persistence.mongo.Organization.OrganizationType;
import org.devgateway.ocds.web.rest.controller.request.OrganizationSearchRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
/**
* @author mpostelnicu
*/
@RestController
public class SupplierSearchController extends AbstractOrganizationSearchController {
@RequestMapping(value = "/api/ocds/organization/supplier/id/{id:^[a-zA-Z0-9\\-]*$}",
method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
@ApiOperation(value = "Finds supplier by the given id")
public Organization byId(@PathVariable final String id) {
return organizationRepository.findByAllIdsAndType(id, Organization.OrganizationType.supplier);
}
/**
* Searches {@link Organization} entities of {@link Organization.OrganizationType}
* {@link Organization.OrganizationType#supplier} by the given text
*
* @param request
* @return
*/
@RequestMapping(value = "/api/ocds/organization/supplier/all",
method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
@ApiOperation(value = "Lists all suppliers in the database. "
+ "Suppliers are organizations that have the label 'supplier' assigned to organization.types array"
+ "Allows full text search using the text parameter.")
public List<Organization> searchText(@Valid final OrganizationSearchRequest request) {
return organizationSearchTextByType(request, OrganizationType.supplier);
}
@RequestMapping(value = "/api/ocds/organization/supplier/count",
method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
@ApiOperation(value = "Counts all suppliers in the database. "
+ "Suppliers are organizations that have the label 'supplier' assigned to organization.types array"
+ "Allows full text search using the text parameter.")
@Override
public Long count(OrganizationSearchRequest request) {
return organizationCountTextByType(request, OrganizationType.supplier);
}
} |
package ru.ifmo.nds.cli;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.beust.jcommander.IValueValidator;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.results.BenchmarkResult;
import org.openjdk.jmh.results.IterationResult;
import org.openjdk.jmh.results.Result;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import oshi.SystemInfo;
import ru.ifmo.nds.IdCollection;
import ru.ifmo.nds.jmh.JMHBenchmark;
import ru.ifmo.nds.rundb.Record;
import ru.ifmo.nds.rundb.Records;
public final class Benchmark extends JCommanderRunnable {
private Benchmark() {}
public static class PositiveIntegerValidator implements IValueValidator<Integer> {
@Override
public void validate(String name, Integer value) throws ParameterException {
if (value <= 0) {
throw new ParameterException("Value for '" + name + "' must be positive, you specified " + value + ".");
}
}
}
public static class ToleranceValidator implements IValueValidator<Double> {
@Override
public void validate(String name, Double value) throws ParameterException {
if (value <= 0 || value >= 1) {
throw new ParameterException("Value for '" + name + "' must be in (0; 1), you specified " + value + ".");
}
}
}
@Parameter(names = "--algorithmId",
required = true,
description = "Specify the algorithm ID to benchmark.")
private String algorithmId;
@Parameter(names = "--forks",
required = true,
description = "Specify the number of forks (different JVM instances) to be used.",
validateValueWith = PositiveIntegerValidator.class)
private Integer forks;
@Parameter(names = "--tolerance",
required = true,
description = "Specify the tolerance used to determine warm-up iteration count, should be in (0; 1).",
validateValueWith = ToleranceValidator.class)
private Double tolerance;
@Parameter(names = "--plateau",
required = true,
description = "Specify the plateau size used to determine warm-up iteration count, should be positive.",
validateValueWith = PositiveIntegerValidator.class)
private Integer plateauSize;
@Parameter(names = "--author",
required = true,
description = "Specify the author of the measurement.")
private String author;
@Parameter(names = "--comment",
required = true,
description = "Specify the comment to the measurement.")
private String comment;
@Parameter(names = "--output",
required = true,
description = "Specify the output file name.")
private String outputFileName;
@Parameter(names = "--append", description = "Append to the output file instead of overwriting it.")
private boolean shouldAppendToOutput;
private static final String[] jmhIds = {
"uniform.hypercube.n10.d2", "uniform.hypercube.n10.d3", "uniform.hypercube.n10.d4",
"uniform.hypercube.n10.d5", "uniform.hypercube.n10.d6", "uniform.hypercube.n10.d7",
"uniform.hypercube.n10.d8", "uniform.hypercube.n10.d9", "uniform.hypercube.n10.d10",
"uniform.hypercube.n100.d2", "uniform.hypercube.n100.d3", "uniform.hypercube.n100.d4",
"uniform.hypercube.n100.d5", "uniform.hypercube.n100.d6", "uniform.hypercube.n100.d7",
"uniform.hypercube.n100.d8", "uniform.hypercube.n100.d9", "uniform.hypercube.n100.d10",
"uniform.hypercube.n1000.d2", "uniform.hypercube.n1000.d3", "uniform.hypercube.n1000.d4",
"uniform.hypercube.n1000.d5", "uniform.hypercube.n1000.d6", "uniform.hypercube.n1000.d7",
"uniform.hypercube.n1000.d8", "uniform.hypercube.n1000.d9", "uniform.hypercube.n1000.d10",
"uniform.hypercube.n10000.d2", "uniform.hypercube.n10000.d3", "uniform.hypercube.n10000.d4",
"uniform.hypercube.n10000.d5", "uniform.hypercube.n10000.d6", "uniform.hypercube.n10000.d7",
"uniform.hypercube.n10000.d8", "uniform.hypercube.n10000.d9", "uniform.hypercube.n10000.d10",
"uniform.hyperplanes.n10.d2.f1", "uniform.hyperplanes.n10.d3.f1", "uniform.hyperplanes.n10.d4.f1",
"uniform.hyperplanes.n10.d5.f1", "uniform.hyperplanes.n10.d6.f1", "uniform.hyperplanes.n10.d7.f1",
"uniform.hyperplanes.n10.d8.f1", "uniform.hyperplanes.n10.d9.f1", "uniform.hyperplanes.n10.d10.f1",
"uniform.hyperplanes.n100.d2.f1", "uniform.hyperplanes.n100.d3.f1", "uniform.hyperplanes.n100.d4.f1",
"uniform.hyperplanes.n100.d5.f1", "uniform.hyperplanes.n100.d6.f1", "uniform.hyperplanes.n100.d7.f1",
"uniform.hyperplanes.n100.d8.f1", "uniform.hyperplanes.n100.d9.f1", "uniform.hyperplanes.n100.d10.f1",
"uniform.hyperplanes.n1000.d2.f1", "uniform.hyperplanes.n1000.d3.f1", "uniform.hyperplanes.n1000.d4.f1",
"uniform.hyperplanes.n1000.d5.f1", "uniform.hyperplanes.n1000.d6.f1", "uniform.hyperplanes.n1000.d7.f1",
"uniform.hyperplanes.n1000.d8.f1", "uniform.hyperplanes.n1000.d9.f1", "uniform.hyperplanes.n1000.d10.f1",
"uniform.hyperplanes.n10000.d2.f1", "uniform.hyperplanes.n10000.d3.f1", "uniform.hyperplanes.n10000.d4.f1",
"uniform.hyperplanes.n10000.d5.f1", "uniform.hyperplanes.n10000.d6.f1", "uniform.hyperplanes.n10000.d7.f1",
"uniform.hyperplanes.n10000.d8.f1", "uniform.hyperplanes.n10000.d9.f1", "uniform.hyperplanes.n10000.d10.f1"
};
private List<Double> getTimes(String algorithmId,
String datasetId,
int warmUps,
int measurements) throws CLIWrapperException, RunnerException {
Options options = new OptionsBuilder()
.forks(1)
.measurementIterations(measurements)
.warmupIterations(warmUps)
.param("datasetId", datasetId)
.param("algorithmId", algorithmId)
.include(JMHBenchmark.class.getName())
.build();
Collection<RunResult> results = new Runner(options).run();
List<Double> times = new ArrayList<>();
for (RunResult result : results) {
for (BenchmarkResult benchmarkResult : result.getBenchmarkResults()) {
BenchmarkParams params = benchmarkResult.getParams();
String myDatasetId = params.getParam("datasetId");
if (!datasetId.equals(myDatasetId)) {
throw new CLIWrapperException("Unable to dig through JMH output: Value for 'datasetId' parameter is '"
+ myDatasetId + "' but expected '" + datasetId + "'", null);
}
String myAlgorithmId = params.getParam("algorithmId");
if (!algorithmId.equals(myAlgorithmId)) {
throw new CLIWrapperException("Unable to dig through JMH output: Value for 'algorithmId' parameter is '"
+ myAlgorithmId + "' but expected '" + algorithmId + "'", null);
}
int count = 0;
for (IterationResult iterationResult : benchmarkResult.getIterationResults()) {
for (Result<?> primary : iterationResult.getRawPrimaryResults()) {
if (primary.getStatistics().getN() != 1) {
throw new CLIWrapperException("Unable to dig through JMH output: getN() != 1", null);
}
if (!primary.getScoreUnit().equals("us/op")) {
throw new CLIWrapperException("Unable to dig through JMH output: getScoreUnit() = " + primary.getScoreUnit(), null);
}
double value = primary.getScore() / 1e6;
times.add(value / IdCollection.getDataset(datasetId).getNumberOfInstances());
++count;
}
}
if (count != measurements) {
throw new CLIWrapperException("Unable to dig through JMH output: Expected "
+ measurements + " measurements, found " + count, null);
}
}
}
return times;
}
private int getWarmUpLength(List<Double> times) {
int minimum = 0;
for (int i = 0; i < times.size(); ++i) {
if (times.get(i) < times.get(minimum)) {
minimum = i;
}
}
double best = times.get(minimum);
int lastCount = 0;
for (int i = times.size() - 1; i >= 0; --i) {
double curr = times.get(i);
if (Math.abs(curr - best) <= tolerance * best) {
++lastCount;
} else {
break;
}
}
if (lastCount >= plateauSize) {
return times.size() - lastCount + plateauSize;
} else {
return -1;
}
}
@Override
protected void run() throws CLIWrapperException {
try {
Path output = Paths.get(outputFileName);
List<Record> allBenchmarks;
if (shouldAppendToOutput && Files.exists(output) && Files.size(output) > 0) {
allBenchmarks = Records.loadFromFile(output);
} else {
allBenchmarks = new ArrayList<>();
Files.write(output, Collections.emptyList());
}
String javaRuntimeVersion = System.getProperty("java.runtime.version");
String cpuModel = new SystemInfo().getHardware().getProcessor().getName();
System.out.println("[info] Java runtime version: '" + javaRuntimeVersion + "'.");
System.out.println("[info] CPU model: '" + cpuModel + "'.");
List<Record> records = new ArrayList<>();
for (String datasetId : jmhIds) {
int warmUpGuess = 5;
List<Record> localRecords = new ArrayList<>();
do {
int warmUpLength;
double bestValue;
System.out.println("[info] Finding the right warm-up length...");
do {
warmUpGuess *= 2;
List<Double> times = getTimes(algorithmId, datasetId, 0, warmUpGuess);
warmUpLength = getWarmUpLength(times);
bestValue = times.stream().mapToDouble(Double::doubleValue).min().orElse(Double.NaN);
if (warmUpLength == -1) {
System.out.println("[warning] " + warmUpGuess
+ " iterations is not enough to find a plateau of size " + plateauSize
+ " with tolerance " + tolerance + ", doubling...");
}
} while (warmUpLength == -1);
System.out.println("[info] warm-up length is " + warmUpLength);
for (int i = 0; i < forks; ++i) {
List<Double> times = getTimes(algorithmId, datasetId, warmUpLength, 1);
LocalDateTime measurementTime = LocalDateTime.now();
double max = times.stream().mapToDouble(Double::doubleValue).max().orElse(Double.NaN);
if (max > (1 + tolerance * 4) * bestValue) {
System.out.println("[warning] something is going wrong, max value " + max
+ " is much worse than best pre-warm-up value " + bestValue + ". Repeating...");
localRecords.clear();
break;
}
localRecords.add(new Record(
algorithmId, datasetId, "JMH",
author, measurementTime, cpuModel, javaRuntimeVersion, times, comment
));
}
} while (localRecords.size() == 0);
records.addAll(localRecords);
}
allBenchmarks.addAll(records);
Records.saveToFile(allBenchmarks, output);
} catch (RunnerException ex) {
throw new CLIWrapperException("Error while running JMH tests.", ex);
} catch (IOException ex) {
throw new CLIWrapperException("Error writing results to output file.", ex);
}
}
public static void main(String[] args) {
JCommanderRunnable.run(new Benchmark(), args);
}
} |
package de.hs_mannheim.IB.SS15.OOT;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import sun.nio.ch.SelChImpl;
import de.hs_mannheim.IB.SS15.OOT.Participants.Desire;
import de.hs_mannheim.IB.SS15.OOT.Participants.Examinee;
public class StudentsGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private GUI gui;
private JPanel south;
private JButton btnAddStudent;
private JButton btnRemoveStudent;
private JButton btnAddDesire;
public static Subject currentSubject;
private SelectSubjectTableModel selectSubjectTableModel;
private JTable selectSubjectTable;
private MainTableModel mainTableModel;
private JTable mainJTable;
public StudentsGUI(GUI gui) {
this.gui = gui;
setTitle("Studenten");
// setup
if (gui.getBackend().getSubjects().size() > 0) {
currentSubject = gui.getBackend().getSubjects().get(0);
}
createLayout();
pack();
setSize(600, 400);
setLocationRelativeTo(gui);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnAddStudent) {
addStudentDialog();
} else if (e.getSource() == btnRemoveStudent) {
removeStudentDialog();
} else if(e.getSource() == btnAddDesire){
addDesireToExaminee();
}
}
private void addDesireToExaminee(){
ArrayList<Examinee> examinee = gui.getBackend().getExaminee();
if(examinee.size()>0){
//TODO pick examinee from list
Examinee selectedExaminee = (Examinee) JOptionPane.showInputDialog(this, "Name des Studenten:", "Wunsch hinzufgen",
JOptionPane.QUESTION_MESSAGE, null, examinee.toArray(), examinee.get(0));
if(selectedExaminee != null){
DesireGUI desire = new DesireGUI(this, selectedExaminee);
}
}
}
private void addStudentDialog() {
String name = JOptionPane.showInputDialog(this, "Vorname des Studenten:", "Student hinzufgen", JOptionPane.PLAIN_MESSAGE);
if (name != null) {
String abbreviation = JOptionPane.showInputDialog(this, "Nachname des Studenten:", "Student hinzufgen", JOptionPane.PLAIN_MESSAGE);
if (abbreviation != null) {
// createExaminee
ArrayList<Desire> desireList = new ArrayList<Desire>();
// TODO (quickFix createExaminee muss gendert werden)
ArrayList<Subject> tempSub = new ArrayList<Subject>();
tempSub.add(currentSubject);
gui.getBackend().createExaminee(name, tempSub, desireList);
mainTableModel.updateData(); // update jTable
}
}
}
private void removeStudentDialog() {
// dropdown Men mit den mglichen Fchern
ArrayList<Subject> subjects = gui.getBackend().getSubjects();
if (subjects.size() > 0) {
Subject selectedSubject = (Subject) JOptionPane.showInputDialog(this, "Vorname des Studenten:", "Studenten entfernen", JOptionPane.QUESTION_MESSAGE, null, subjects.toArray(), subjects.get(0));
if (selectedSubject != null) {
// TODO removeSubject aus Backend updaten
// gui.getBackend().removeSubject(selectedSubject);
for (int i = 0; i < subjects.size(); i++) {
if (subjects.get(i).equals(selectedSubject)) {
subjects.remove(i);
mainTableModel.updateData();
return;
}
}
}
} else {
JOptionPane.showMessageDialog(this, "Es sind noch keine Studenten vorhanden.", "Studenten entfernen", JOptionPane.ERROR_MESSAGE);
}
}
private void createLayout() {
// set Layout
getContentPane().setLayout(new BorderLayout());
// CENTER Panel
createSubjectTable();
createMainTable();
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(selectSubjectTable), new JScrollPane(mainJTable));
splitPane.setDividerLocation(150);
getContentPane().add(splitPane, BorderLayout.CENTER);
// SOUTH Panel
createSouthButtons();
getContentPane().add(south, BorderLayout.SOUTH);
}
private void createSubjectTable() {
mainTableModel = new MainTableModel(gui);
mainJTable = new JTable(mainTableModel);
}
private void createMainTable() {
selectSubjectTableModel = new SelectSubjectTableModel(gui);
selectSubjectTable = new JTable(selectSubjectTableModel);
selectSubjectTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
currentSubject = gui.getBackend().getSubjects().get(selectSubjectTable.getSelectedRow()); // update jTable
mainTableModel.updateData();
// TODO update table :(
}
});
}
private void createSouthButtons() {
south = new JPanel();
south.setLayout(new GridLayout(1, 3));
btnAddStudent = new JButton("Student hinzufgen");
btnAddStudent.addActionListener(this);
south.add(btnAddStudent);
btnRemoveStudent = new JButton("Student lschen");
btnRemoveStudent.addActionListener(this);
south.add(btnRemoveStudent);
btnAddDesire = new JButton("Wunsch hinzufgen");
btnAddDesire.addActionListener(this);
south.add(btnAddDesire);
}
}
class SelectSubjectTableModel extends AbstractTableModel {
private GUI mainGUI;
private ArrayList<Subject> subjects;
private final int COLUMS = 1;
SelectSubjectTableModel(GUI mainGUI) {
this.mainGUI = mainGUI;
subjects = mainGUI.getBackend().getSubjects();
if (subjects != null && subjects.size() > 0 && subjects.get(0) != null) {
StudentsGUI.currentSubject = subjects.get(0);
}
}
@Override
public int getRowCount() {
return subjects.size();
}
@Override
public int getColumnCount() {
return COLUMS;
}
@Override
public String getColumnName(int col) {
return "Fcher";
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return subjects.get(rowIndex).getName() + " (" + subjects.get(rowIndex).getAbbreviation() + ")";
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
class MainTableModel extends AbstractTableModel {
private GUI mainGUI;
private ArrayList<Examinee> examinee;
private final int COLUMS = 3;
MainTableModel(GUI mainGUI) {
this.mainGUI = mainGUI;
examinee = new ArrayList<Examinee>();
updateData();
}
public void updateData() {
examinee.clear();
for (int i = 0; i < mainGUI.getBackend().getExaminee().size(); i++) {
if (mainGUI.getBackend().getExaminee().get(i) != null && mainGUI.getBackend().getExaminee().get(i).hasSubject(StudentsGUI.currentSubject)) {
examinee.add(mainGUI.getBackend().getExaminee().get(i));
}
}
fireTableDataChanged(); // Notifies all listeners that all cell values in the table's rows may have changed.
}
@Override
public int getRowCount() {
return examinee.size();
}
@Override
public int getColumnCount() {
return COLUMS;
}
@Override
public String getColumnName(int col) {
if (col == 0) {
return "Vorname";
} else if (col == 1) {
return "Nachname";
} else if (col == 2) {
return "Wnsche";
}
return null;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return examinee.get(rowIndex).getName();
} else if (columnIndex == 1) {
return examinee.get(rowIndex).getName();
} else if (columnIndex == 1) {
return examinee.get(rowIndex).getDesires();
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.tobi.rccar;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.event.*;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.eventprocessing.FilterChain;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.graphics.FrameAnnotater;
import javax.media.opengl.*;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.*;
import javax.swing.*;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.util.*;
import java.util.Observable;
import java.util.Observer;
import java.beans.*;
import java.io.*;
import com.sun.opengl.util.*;
/**
*
* @author braendch
*
*/
public class HingeLineTracker extends EventFilter2D implements FrameAnnotater, Observer {
private float hingeThreshold=getPrefs().getFloat("LineTracker.hingeThreshold",2.5f);
{setPropertyTooltip("hingeThreshold","the threshold for the hinge to react");}
private float ellipseFactor=getPrefs().getFloat("LineTracker.ellipseFactor",1.1f);
{setPropertyTooltip("ellipseFactor","the size of the attention ellipse");}
private float attentionFactor=getPrefs().getFloat("LineTracker.attentionFactor",2);
{setPropertyTooltip("attentionFactor","how much is additionally added to the accumArray if the attention is on a certain spike");}
private float hingeDecayFactor=getPrefs().getFloat("LineTracker.hingeDecayFactor",0.6f);
{setPropertyTooltip("hingeDecayFactor","hinge accumulator cells are multiplied by this factor before each frame, 0=no memory, 1=infinite memory");}
private float attentionDecayFactor=getPrefs().getFloat("LineTracker.attentionDecayFactor",0.6f);
{setPropertyTooltip("attentionDecayFactor","the slope of attention decay, 0=no memory, 1=infinite memory");}
private int shiftSpace=getPrefs().getInt("LineTracker.shiftSpace",5);
{setPropertyTooltip("shiftSpace","minimal distance between paoli hinge and seperation");}
private boolean showRowWindow=true;
{setPropertyTooltip("showRowWindow","");}
private float[][] accumArray;
private float[][][] attentionArray;
private float[] sideMax;
private float[] hingeMax;
private int[] maxIndex;
private int[] enterMaxIndex;
private int[] leaveMaxIndex;
private int[] hingeArray;
private int[] seperator ;
private boolean[] isPaoli;
private float attentionMax;
private int sx;
private int sy;
private int hingeNumber = 12;
private int height = 4;
private int width = 4; //should be even
FilterChain preFilterChain;
private OrientationCluster orientationCluster;
public HingeLineTracker(AEChip chip) {
super(chip);
//build hierachy
preFilterChain = new FilterChain(chip);
orientationCluster = new OrientationCluster(chip);
this.setEnclosedFilter(orientationCluster);
orientationCluster.setEnclosed(true, this);
//xYFilter.getPropertyChangeSupport().addPropertyChangeListener("filterEnabled",this);
chip.getCanvas().addAnnotator(this);
initFilter();
resetFilter();
}
private void checkMaps(){
//it has to be checked if the VectorMap fits on the actual chip
if(accumArray==null
|| accumArray.length!=hingeNumber
|| accumArray[0].length!=chip.getSizeX()) {
allocateMaps();
}
}
synchronized private void allocateMaps() {
//the VectorMap is fitted on the chip size
if(!isFilterEnabled()) return;
log.info("HingeLineTracker.allocateMaps()");
sx=chip.getSizeX();
sy=chip.getSizeY();
if(chip!=null){
accumArray= new float[hingeNumber][sx];
attentionArray= new float[sx+1][sy][2];
hingeMax= new float[hingeNumber];
sideMax= new float[2];
enterMaxIndex= new int[2];
leaveMaxIndex= new int[2];
hingeArray= new int[hingeNumber];
maxIndex= new int[hingeNumber];
seperator = new int[hingeNumber/2+1];
isPaoli= new boolean[hingeNumber];
}
resetFilter();
}
synchronized public void resetFilter() {
if(!isFilterEnabled()) return;
if(accumArray!=null){
for(int i=0;i<accumArray.length;i++) Arrays.fill(accumArray[i],0);
for(int i=0;i<sx+1;i++) for(int j=0; j<sy; j++) Arrays.fill(attentionArray[i][j],0);
Arrays.fill(hingeMax,Float.NEGATIVE_INFINITY);
Arrays.fill(hingeArray,0);
Arrays.fill(maxIndex, 0);
Arrays.fill(sideMax,0);
Arrays.fill(enterMaxIndex,0);
Arrays.fill(leaveMaxIndex,0);
Arrays.fill(seperator,chip.getSizeX()/(2*width));
log.info("HingeLineTracker.reset!");
}else{
return;
}
}
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if(!isFilterEnabled()) return in;
if(getEnclosedFilter()!=null) in=getEnclosedFilter().filterPacket(in);
if(getEnclosedFilterChain()!=null) in=getEnclosedFilterChain().filterPacket(in);
int n=in.getSize();
if(n==0) return in;
checkMaps();
hingeArray[0] = 15;
hingeArray[1] = 15;
hingeArray[2] = 30;
hingeArray[3] = 30;
hingeArray[4] = 45;
hingeArray[5] = 45;
hingeArray[6] = 60;
hingeArray[7] = 60;
hingeArray[8] = 75;
hingeArray[9] = 75;
hingeArray[10] = 90;
hingeArray[11] = 90;
for(BasicEvent e:in){
//for each event it is checked if it belongs to the rf of an row cell
for(int i=0;i<hingeNumber;i+=2){
if(e.y <= hingeArray[i]+height && e.y >= hingeArray[i]-height ){
if(e.y<40){
if(e.x/width<(seperator[i/2])){
if(attentionArray[e.x][e.y][0]>0.01)
updateHingeAccumulator(i,e.x/width,0);
} else {
if(attentionArray[e.x][e.y][1]>0.01)
updateHingeAccumulator(i+1,e.x/width,1);
}
}else{
if(e.x/width<(seperator[i/2])){
updateHingeAccumulator(i,e.x/width,0);
} else {
updateHingeAccumulator(i+1,e.x/width,1);
}
}
}
}
}
decayAttentionArray();
//the attention has to be
for(int i=0;i<hingeNumber;i++){
if(isPaoli[i] && isPaoli[i+2]){
} else {
isPaoli[i]=false;
}
}
decayAccumArray();
modulateAttention();
updateSeperation();
//updatePaoli();
if(showRowWindow) {
checkAccumFrame();
accumCanvas.repaint();
}
return in;
}
private void updateHingeAccumulator(int hingeNumber, int x, int leori) {
float f=accumArray[hingeNumber][x];
f++;
f=f+attentionFactor*attentionArray[x][hingeArray[hingeNumber]][leori];
accumArray[hingeNumber][x]=f; // update the accumulator
}
private void decayAccumArray() {
if(accumArray==null) return;
sideMax[0]*=hingeDecayFactor;
sideMax[1]*=hingeDecayFactor;
enterMaxIndex[0]=0;
enterMaxIndex[1]=0;
leaveMaxIndex[0]=0;
leaveMaxIndex[1]=0;
for(int hinge=0; hinge<hingeNumber; hinge++){
hingeMax[hinge]*=hingeDecayFactor;
float[] f=accumArray[hinge];
for(int y=0;y<f.length/width;y++){
float fval=f[y];
fval*=hingeDecayFactor;
if(fval>hingeMax[hinge]) {
maxIndex[hinge]=y;
hingeMax[hinge]=fval;
isPaoli[hinge]=true;
hingeMax[hinge+1-hinge%2*2]=fval;
}
f[y]=fval;
}
if(accumArray[hinge][maxIndex[hinge]]<hingeThreshold){
maxIndex[hinge]=hinge%2*sx/width;
isPaoli[hinge]=false;
}
//enter-leave update
if(accumArray[hinge][1]>sideMax[0]){
sideMax[0]=accumArray[hinge][1];
if(hinge%2==0){
enterMaxIndex[0]=hingeArray[hinge];
}else{
leaveMaxIndex[1]=hingeArray[hinge];
}
}
if(accumArray[hinge][sx/width-1]>sideMax[1]){
sideMax[1]=accumArray[hinge][sx/width-1];
if(hinge%2==1){
enterMaxIndex[1]=hingeArray[hinge];
}else{
leaveMaxIndex[0]=hingeArray[hinge];
}
}
}
}
private void decayAttentionArray() {
if(accumArray==null) return;
attentionMax=0;
for(int x=0; x<sx; x++){
for(int y=0; y<sy; y++){
for(int leori=0; leori<2; leori++){
attentionArray[x][y][leori]*=attentionDecayFactor;
if(attentionArray[x][y][leori]>attentionMax){
attentionMax=attentionArray[x][y][leori];
}
}
}
}
}
private void modulateAttention(){
for(int i=0; i<hingeNumber; i++){
if(isPaoli[i]){
int left;
int right;
int leftY;
int rightY;
if(i>=0 && i+2<hingeNumber && isPaoli[i+2]){
float distance = (float)Math.sqrt((maxIndex[i]-maxIndex[i+2])*(maxIndex[i]-maxIndex[i+2])+(hingeArray[i]-hingeArray[i+2])*(hingeArray[i]-hingeArray[i+2]));
float radius = distance*ellipseFactor;
if(maxIndex[i]<maxIndex[i+2]){
left = 2*maxIndex[i]-maxIndex[i+2];
leftY = 2*hingeArray[i]-hingeArray[i+2];
right = maxIndex[i];
rightY = hingeArray[i];
} else {
left = maxIndex[i];
leftY = hingeArray [i];
right = 2*maxIndex[i]-maxIndex[i+2];
rightY = 2*hingeArray[i]-hingeArray[i+2];
}
for(int x=(int)(left-radius/2); x<(int)(right+radius/2); x++){
for(int y=(int)(2*hingeArray[i]-hingeArray[i+2]-radius/2); y<hingeArray[i]+radius/2; y++){
if((float)(Math.sqrt((x-left)*(x-left)+(y-leftY)*(y-leftY))+
Math.sqrt((x-right)*(x-right)+(y-rightY)*(y-rightY)))<radius){
for(int px=0; px<width; px++){
if(width*x+px>=0 && y>=0 && width*x+px<sx && y<sy)
attentionArray[width*x+px][y][i%2]=attentionArray[width*x+px][y][i%2]+1;
}
}
}
}
}
if(i-2>=0 && i+2<hingeNumber && isPaoli[i-2]){
float distance = (float)Math.sqrt((maxIndex[i]-maxIndex[i-2])*(maxIndex[i]-maxIndex[i-2])+(hingeArray[i]-hingeArray[i-2])*(hingeArray[i]-hingeArray[i-2]));
float radius = distance*ellipseFactor;
if(maxIndex[i]<maxIndex[i-2]){
left = 2*maxIndex[i]-maxIndex[i-2];
leftY = 2*hingeArray[i]-hingeArray[i-2];
right = maxIndex[i];
rightY = hingeArray[i];
} else {
left = maxIndex[i];
leftY = hingeArray [i];
right = 2*maxIndex[i]-maxIndex[i-2];
rightY = 2*hingeArray[i]-hingeArray[i-2];
}
for(int x=(int)(left-radius/2); x<(int)(right+radius/2); x++){
for(int y=(int)(hingeArray[i]-radius/2); y<(int)(2*hingeArray[i]-hingeArray[i-2]+radius/2); y++){
if((float)(Math.sqrt((x-left)*(x-left)+(y-leftY)*(y-leftY))+
Math.sqrt((x-right)*(x-right)+(y-rightY)*(y-rightY)))<radius){
for(int px=0; px<width; px++){
if(width*x+px>=0 && y>=0 && width*x+px<sx && y<sy)
attentionArray[width*x+px][y][i%2]=attentionArray[width*x+px][y][i%2]+1;
}
}
}
}
}
}
}
}
public void updateSeperation(){
for(int i=0; i<hingeNumber/2; i++){
//check if seperator should be pulled back to the middle
if(maxIndex[2*i]*width<sx/2 && isPaoli[2*i]){
seperator[i]= sx/(2*width);
}
if(maxIndex[2*i+1]*width>sx/2 && isPaoli[2*i+1]){
seperator[i]= sx/(2*width);
}
//check if seperator should be pushed away
while(attentionArray[width*seperator[i]][hingeArray[2*i]][0]-0.01>attentionArray[width*seperator[i]][hingeArray[2*i]][1]+0.01 && (seperator[i])*width<sx ){
seperator[i]=seperator[i]+1;
}
while(attentionArray[width*seperator[i]][hingeArray[2*i]][0]+0.01<attentionArray[width*seperator[i]][hingeArray[2*i]][1] && seperator[i]>0){
seperator[i]=seperator[i]-1;
}
//check if seperator is inbetween two parts of a line
if(2*i+2 < hingeNumber && 2*i-2>0 && isPaoli[2*i-2] && isPaoli[2*i+2] && seperator[i]<(maxIndex[2*i-2]+maxIndex[2*i+2])/2){
maxIndex[2*i]=(maxIndex[2*i-2]+maxIndex[2*i+2])/2;
seperator[i]=(seperator[i-1]+seperator[i+1])/2;
isPaoli[2*i+2]=true;
}
if(2*i+3 < hingeNumber && 2*i-1>0 && isPaoli[2*i-1] && isPaoli[2*i+3] && seperator[i]>(maxIndex[2*i-1]+maxIndex[2*i+3])/2){
maxIndex[2*i+1]=(maxIndex[2*i-1]+maxIndex[2*i+3])/2;
isPaoli[2*i+1]=true;
seperator[i]=(seperator[i-1]+seperator[i+1])/2;
}
}
}
public void updatePaoli() {
if(enterMaxIndex[0]!=0){
for(int i=0; i<hingeNumber; i+=2){
if(hingeArray[i]<enterMaxIndex[0])
isPaoli[i]=false;
seperator[i/2]=0;
Arrays.fill(accumArray[i],0);
}
}
if(enterMaxIndex[1]!=0){
for(int i=1; i<hingeNumber; i+=2){
if(hingeArray[i]<enterMaxIndex[0])
isPaoli[i]=false;
seperator[i/2]=sx/(2*width);
Arrays.fill(accumArray[i],0);
}
}
}
GLU glu=null;
GLUquadric wheelQuad;
public void annotate(GLAutoDrawable drawable) {
if(!isFilterEnabled()) return;
if(hingeArray == null) return;
GL gl=drawable.getGL();
gl.glColor3f(1,1,1);
gl.glLineWidth(3);
if(glu==null) glu=new GLU();
if(wheelQuad==null) wheelQuad = glu.gluNewQuadric();
gl.glPushMatrix();
//attention
gl.glPointSize(2);
for(int x=0; x<sx; x++){
for(int y=0; y<sy; y++){
gl.glBegin(GL.GL_POINTS);
gl.glColor3f(attentionArray[x][y][0]/attentionMax,attentionArray[x][y][1]/attentionMax,(attentionArray[x][y][0]+attentionArray[x][y][1])/attentionMax);
gl.glVertex2i(x,y);
gl.glEnd();
}
}
//seperator
gl.glPointSize(8);
gl.glColor3f(1,1,1);
for(int i=0; i<hingeNumber/2;i++){
gl.glBegin(GL.GL_POINTS);
gl.glVertex2f(width*seperator[i], hingeArray[2*i]);
gl.glEnd();
}
gl.glBegin(GL.GL_LINE_STRIP);
for(int i=0; i<hingeNumber/2;i++){
gl.glVertex2i(width*seperator[i], hingeArray[2*i]);
}
gl.glEnd();
//points
for(int i=0; i<hingeNumber;i++){
gl.glColor3f(1-i%2,i%2,1);
gl.glBegin(GL.GL_POINTS);
gl.glVertex2f(width*maxIndex[i], hingeArray[i]);
gl.glEnd();
}
//left line
gl.glColor3f(1,0,1);
gl.glBegin(GL.GL_LINE_STRIP);
for(int i=0; i<hingeNumber;i+=2){
if(isPaoli[i]){
gl.glVertex2i(width*maxIndex[i],hingeArray[i]);
}
}
//right line
gl.glEnd();
gl.glColor3f(0,1,1);
gl.glBegin(GL.GL_LINE_STRIP);
for(int i=1; i<hingeNumber;i+=2){
if(isPaoli[i]){
gl.glVertex2i(width*maxIndex[i],hingeArray[i]);
}
}
gl.glEnd();
gl.glPopMatrix();
}
void checkAccumFrame(){
if(showRowWindow && (accumFrame==null || (accumFrame!=null && !accumFrame.isVisible()))) createAccumFrame();
}
JFrame accumFrame=null;
GLCanvas accumCanvas=null;
void createAccumFrame(){
accumFrame=new JFrame("Hinge accumulator");
accumFrame.setPreferredSize(new Dimension(400,400));
accumCanvas=new GLCanvas();
accumCanvas.addGLEventListener(new GLEventListener(){
public void init(GLAutoDrawable drawable) {
}
synchronized public void display(GLAutoDrawable drawable) {
if(accumArray==null) return;
GL gl=drawable.getGL();
gl.glLoadIdentity();
gl.glScalef(width*drawable.getWidth()/sx,drawable.getHeight()/sy,1);
gl.glClearColor(0,0,0,0);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
//left
for(int i=0;i<hingeNumber;i+=2){
for(int j=0;j<seperator[i/2];j++){
float f=accumArray[i][j]/hingeMax[i];
gl.glColor3f(f,0,f);
gl.glRectf(j,hingeArray[i]-height,j+1,hingeArray[i]+height);
}
gl.glColor3f(1,0,0);
gl.glRectf(maxIndex[i],hingeArray[i]-height,maxIndex[i]+1,hingeArray[i]+height);
}
//right
for(int i=1;i<hingeNumber;i+=2){
for(int j=seperator[(i-1)/2];j<accumArray[i].length/width;j++){
float f=accumArray[i][j]/hingeMax[i];
gl.glColor3f(0,f,f);
gl.glRectf(j,hingeArray[i]-height,j+1,hingeArray[i]+height);
}
gl.glColor3f(1,0,0);
gl.glRectf(maxIndex[i],hingeArray[i]-height,maxIndex[i]+1,hingeArray[i]+height);
}
//seperator
for(int i=0;i<hingeNumber/2;i++){
gl.glColor3f(1,1,1);
gl.glRectf(seperator[i],hingeArray[2*i]-height,seperator[i]+1,hingeArray[2*i]+height);
}
//enter,leaveMax
// left side
if(sideMax[0]>hingeThreshold)
if(enterMaxIndex[0]!=0){
gl.glColor3f(0.5f,0,1);
gl.glRectf(0,enterMaxIndex[0]-height,1,enterMaxIndex[0]+height);
}
if(leaveMaxIndex[1]!=0){
gl.glColor3f(0,0.5f,1);
gl.glRectf(0,leaveMaxIndex[1]-height,1,leaveMaxIndex[1]+height);
}
//right side
if(sideMax[1]>hingeThreshold)
if(enterMaxIndex[1]!=0){
gl.glColor3f(0,1,0.5f);
gl.glRectf((sx/width),enterMaxIndex[1]-height,(sx/width)+1,enterMaxIndex[1]+height);
}
if(leaveMaxIndex[0]!=0){
gl.glColor3f(1,0,0.5f);
gl.glRectf((sx/width),leaveMaxIndex[0]-height,(sx/width)+1,leaveMaxIndex[0]+height);
}
int error=gl.glGetError();
if(error!=GL.GL_NO_ERROR){
if(glu==null) glu=new GLU();
log.warning("GL error number "+error+" "+glu.gluErrorString(error));
}
}
synchronized public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
GL gl=drawable.getGL();
final int B=10;
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity(); // very important to load identity matrix here so this works after first resize!!!
gl.glOrtho(-B,drawable.getWidth()+B,-B,drawable.getHeight()+B,10000,-10000);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glViewport(0,0,width,height);
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
}
});
accumFrame.getContentPane().add(accumCanvas);
accumFrame.pack();
accumFrame.setVisible(true);
}
public Object getFilterState() {
return null;
}
public void initFilter() {
resetFilter();
}
public void annotate(float[][][] frame) {
}
public void annotate(Graphics2D g) {
}
public boolean isShowRowWindow() {
return showRowWindow;
}
synchronized public void setShowRowWindow(boolean showRowWindow) {
this.showRowWindow = showRowWindow;
}
public void update(Observable o, Object arg){
resetFilter();
}
public int getShiftSpace() {
return shiftSpace;
}
public void setShiftSpace(int shiftSpace) {
this.shiftSpace = shiftSpace;
getPrefs().putInt("LineTracker.shiftSpace",shiftSpace);
}
public float getHingeThreshold() {
return hingeThreshold;
}
public void setHingeThreshold(float hingeThreshold) {
this.hingeThreshold = hingeThreshold;
getPrefs().putFloat("LineTracker.hingeThreshold",hingeThreshold);
}
public float getEllipseFactor() {
return ellipseFactor;
}
public void setEllipseFactor(float ellipseFactor) {
if(ellipseFactor<1)ellipseFactor=1;else if(ellipseFactor>10)ellipseFactor=10;
this.ellipseFactor = ellipseFactor;
getPrefs().putFloat("LineTracker.ellipseFactor",ellipseFactor);
}
public float getHingeDecayFactor() {
return hingeDecayFactor;
}
public void setAttentionFactor(float attentionFactor) {
this.attentionFactor = attentionFactor;
getPrefs().putFloat("LineTracker.attentionFactor",attentionFactor);
}
public float getAttentionFactor() {
return attentionFactor;
}
public void setHingeDecayFactor(float hingeDecayFactor) {
if(hingeDecayFactor<0)hingeDecayFactor=0;else if(hingeDecayFactor>1)hingeDecayFactor=1;
this.hingeDecayFactor = hingeDecayFactor;
getPrefs().putFloat("LineTracker.hingeDecayFactor",hingeDecayFactor);
}
public float getAttentionDecayFactor() {
return attentionDecayFactor;
}
public void setAttentionDecayFactor(float attentionDecayFactor) {
if(attentionDecayFactor<0)attentionDecayFactor=0;else if(attentionDecayFactor>1)attentionDecayFactor=1;
this.attentionDecayFactor = attentionDecayFactor;
getPrefs().putFloat("LineTracker.attentionDecayFactor",attentionDecayFactor);
}
} |
package goplaces.apis;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import goplaces.models.CustomizeRouteQuery;
import org.json.JSONObject;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
@Path("/boxrouteworkerapi")
public class BoxRouteWorkerAPI{
@Context
UriInfo uriInfo;
@Context
Request request;
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String addNewTask(CustomizeRouteQuery route,
@Context HttpServletResponse servletResponse) throws IOException {
try{
String route_id = route.getRouteID();
String radius = String.valueOf(route.getRadius());
StringBuilder keywords = new StringBuilder();
if(route.getKeywords().length > 5)
return new JSONObject().append("status","fail").append("message","too many keywords").toString();
for(String keyword : route.getKeywords())
keywords.append(keyword + ",");
System.out.println(1 + " Route ID " + Long.parseLong(route_id));
Entity originalRouteEntity = datastore.get(KeyFactory.createKey("Route", Long.parseLong(route_id)));
if(originalRouteEntity == null){
return new JSONObject().append("status", "fail").append("message", "route not found in datastore" +
".").toString();
}
Text originalRouteJsonText = (Text)originalRouteEntity.getProperty("routeJSON");
if(originalRouteJsonText == null){
return new JSONObject().append("status", "fail").append("message", "route not found in datastore" +
".").toString();
}
String originalRouteJSON = originalRouteJsonText.getValue();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder.withUrl("/boxroute").param("originalroutejsontext", originalRouteJSON)
.param("routeid", route_id).param("radius", radius)
.param("keywords", keywords.toString()));
return new JSONObject().append("status", "ok").append("message", "task fired off.").toString();
}
catch(Exception e){
e.printStackTrace();
}
return new JSONObject().append("status", "fail").append("message","something went wrong").toString();
}
@GET
@Path("{route_id}")
@Produces(MediaType.APPLICATION_JSON)
public String getPlace(@PathParam("route_id") String routeID) {
JSONObject reply = new JSONObject();
try{
Entity result2 = datastore.get(KeyFactory.createKey("Route", Long.parseLong(routeID)));
if(result2 == null || result2.getProperty("placesJSON") == null)
return reply.append("status", "fail").append("message", "Could not find places around the given route" +
" in datastore.").append("routeID", routeID).toString();
reply.append("status", "OK");
reply.append("message", "Found in datastore.");
reply.append("routeID", routeID);
reply.append("placesJSON",((Text)(result2.getProperty("placesJSON"))).getValue());
return reply.toString();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
return new JSONObject().append("status","fail").append("message","no such route")
.toString();
}
}
} |
package de.jungblut.classification.meta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import de.jungblut.classification.AbstractClassifier;
import de.jungblut.classification.Classifier;
import de.jungblut.classification.ClassifierFactory;
import de.jungblut.datastructure.ArrayUtils;
import de.jungblut.math.DoubleVector;
import de.jungblut.math.dense.DenseDoubleVector;
import de.jungblut.partition.BlockPartitioner;
import de.jungblut.partition.Boundaries.Range;
/**
* Implementation of vote ensembling.
*
* @author thomas.jungblut
*
*/
public final class Voting extends AbstractClassifier {
public static enum CombiningType {
MAJORITY, AVERAGE, MAX, MIN, MEDIAN
}
private final CombiningType type;
private final Classifier[] classifier;
private final int threads;
private final boolean verbose;
public Voting(CombiningType type, ClassifierFactory factory, int models,
int threads, boolean verbose) {
this.threads = threads;
this.verbose = verbose;
this.type = type;
this.classifier = new Classifier[models];
for (int i = 0; i < models; i++) {
this.classifier[i] = factory.newInstance();
}
}
public Voting(CombiningType type, ClassifierFactory factory, int models,
boolean verbose) {
this(type, factory, models, Runtime.getRuntime().availableProcessors(),
verbose);
}
@Override
public void train(DoubleVector[] features, DenseDoubleVector[] outcome) {
ExecutorService pool = Executors.newFixedThreadPool(threads);
ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<>(
pool);
// each of the classifiers get a randomized chunk of the training set
ArrayUtils.multiShuffle(features, outcome);
List<Range> partitions = new ArrayList<>(new BlockPartitioner().partition(
classifier.length, features.length).getBoundaries());
final int[] splitRanges = new int[classifier.length + 1];
for (int i = 1; i < classifier.length; i++) {
splitRanges[i] = partitions.get(i).getStart();
}
splitRanges[classifier.length] = features.length - 1;
if (verbose) {
System.out.println("Computed split ranges for 0-" + features.length
+ ": " + Arrays.toString(splitRanges) + "\n");
}
for (int i = 0; i < classifier.length; i++) {
completionService.submit(new TrainingWorker(classifier[i], ArrayUtils
.subArray(features, splitRanges[i], splitRanges[i + 1]), ArrayUtils
.subArray(outcome, splitRanges[i], splitRanges[i + 1])));
}
try {
// let the training happen meanwhile wait for the result
for (int i = 0; i < classifier.length; i++) {
completionService.take();
if (verbose) {
System.out.println("Finished with training classifier " + (i + 1)
+ " of " + classifier.length);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
pool.shutdownNow();
}
if (verbose) {
System.out.println("Successfully finished training!");
}
}
@Override
public DoubleVector predict(DoubleVector features) {
// predict
DoubleVector[] result = new DoubleVector[classifier.length];
for (int i = 0; i < classifier.length; i++) {
result[i] = classifier[i].predict(features);
}
int possibleOutcomes = result[0].getDimension() == 1 ? 2 : result[0]
.getDimension();
DenseDoubleVector toReturn = new DenseDoubleVector(
possibleOutcomes == 2 ? 1 : possibleOutcomes);
// now combine the results based on the rule
switch (type) {
case MAJORITY:
double[] histogram = new double[possibleOutcomes];
for (int i = 0; i < classifier.length; i++) {
histogram[classifier[i].getPredictedClass(features)]++;
}
if (possibleOutcomes == 2) {
toReturn.set(0, ArrayUtils.maxIndex(histogram));
} else {
toReturn.set(ArrayUtils.maxIndex(histogram), 1d);
}
break;
default:
throw new UnsupportedOperationException("Type " + type
+ " isn't supported yet!");
}
return toReturn;
}
final class TrainingWorker implements Callable<Boolean> {
private final Classifier cls;
private final DoubleVector[] features;
private final DenseDoubleVector[] outcome;
TrainingWorker(Classifier classifier, DoubleVector[] features,
DenseDoubleVector[] outcome) {
cls = classifier;
this.features = features;
this.outcome = outcome;
}
@Override
public Boolean call() throws Exception {
cls.train(features, outcome);
return true;
}
}
} |
package de.mycrobase.ssim.ed.app;
import ssim.util.MathExt;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.audio.AudioNode;
import de.mycrobase.ssim.ed.GameMode;
import de.mycrobase.ssim.ed.GameModeListener;
import de.mycrobase.ssim.ed.weather.Weather;
import de.mycrobase.ssim.ed.weather.ext.PrecipitationType;
public class AudioAppState extends BasicAppState implements GameModeListener {
private static final float UpdateInterval = 0.1f; // in seconds
// exists only while AppState is attached
private AudioNode wind;
private AudioNode rainMedium;
private AudioNode rainHeavy;
public AudioAppState() {
super(UpdateInterval);
}
@Override
public void initialize(AppStateManager stateManager, Application baseApp) {
super.initialize(stateManager, baseApp);
wind = loadEnvSound("audio/wind.ogg");
updateWind();
rainMedium = loadEnvSound("audio/rain-medium.ogg");
rainHeavy = loadEnvSound("audio/rain-heavy.ogg");
updateRain();
// manual call to avoid code duplication
gameModeChanged(null, getApp().getCurrentMode());
getApp().addGameModeListener(this);
}
@Override
public void update(float dt) {
super.update(dt);
// update listener (OpenAL term for ears) by camera position
getApp().getListener().setLocation(getApp().getCamera().getLocation());
getApp().getListener().setRotation(getApp().getCamera().getRotation());
}
@Override
protected void intervalUpdate(float dt) {
updateWind();
updateRain();
}
@Override
public void cleanup() {
super.cleanup();
wind.stop();
rainMedium.stop();
rainHeavy.stop();
wind = null;
rainMedium = null;
rainHeavy = null;
}
@Override
public void gameModeChanged(GameMode oldMode, GameMode newMode) {
if(newMode == GameMode.Paused) {
wind.pause();
rainMedium.pause();
rainHeavy.pause();
} else {
wind.play();
rainMedium.play();
rainHeavy.play();
}
}
private Weather getWeather() {
return getState(WeatherAppState.class).getWeather();
}
private float getSoundEffectVolume() {
return getApp().getSettingsManager().getFloat("sound.effect.volume");
}
private void updateWind() {
float strength = getWeather().getFloat("wind.strength");
float minAudibleStrength = 3f; // below is calm
float maxAudibleStrength = 30f; // near gale and more
float windVolume = (float) MathExt.interpolateLinear(0f, 1f,
(strength-minAudibleStrength) / (maxAudibleStrength-minAudibleStrength));
wind.setVolume(windVolume * getSoundEffectVolume());
}
private void updateRain() {
PrecipitationType curType =
PrecipitationType.fromId(getWeather().getInt("precipitation.form"));
float intensity = getWeather().getFloat("precipitation.intensity");
float rainMediumVolume;
float rainHeavyVolume;
if(curType == PrecipitationType.Rain) {
rainMediumVolume = getRainMediumVolume(intensity);
rainHeavyVolume = getRainHeavyVolume(intensity);
} else {
rainMediumVolume = 0f;
rainHeavyVolume = 0f;
}
rainMedium.setVolume(rainMediumVolume * getSoundEffectVolume());
rainHeavy.setVolume(rainHeavyVolume * getSoundEffectVolume());
}
private AudioNode loadEnvSound(String file) {
AudioNode a = new AudioNode(
getApp().getAssetManager(), file, false);
a.setLooping(true);
// there is btw no need to attach a non-positional AudioNode to the
a.setPositional(false);
return a;
}
private float getRainMediumVolume(float intensity) {
if(0.0f <= intensity && intensity < 0.2f) {
return (float) MathExt.interpolateLinear(0f, 1f, (intensity-0.0f) / (0.2f-0.0f));
}
if(0.2f <= intensity && intensity < 0.7f) {
return 1f;
}
if(0.7f <= intensity && intensity < 0.8f) {
return (float) MathExt.interpolateLinear(1f, 0f, (intensity-0.7f) / (0.8f-0.7f));
}
if(0.8f <= intensity && intensity <= 1.0f) {
return 0f;
}
throw new IllegalArgumentException("intensity not in range [0,1]");
}
private float getRainHeavyVolume(float intensity) {
if(0.0f <= intensity && intensity < 0.7f) {
return 0f;
}
if(0.7f <= intensity && intensity < 0.8f) {
return (float) MathExt.interpolateLinear(0f, 1f, (intensity-0.7f) / (0.8f-0.7f));
}
if(0.8f <= intensity && intensity <= 1.0f) {
return 1f;
}
throw new IllegalArgumentException("intensity not in range [0,1]");
}
} |
package de.mycrobase.ssim.ed.app;
import ssim.util.MathExt;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
import de.mycrobase.ssim.ed.mesh.OceanSurface;
import de.mycrobase.ssim.ed.util.TempVars;
public class OceanAppState extends BasicAppState {
private static final float UpdateInterval = 5f; // in seconds
private static final float GridStep = 400f; // in m
private static final int GridSize = 64;
private static final int NumGridTiles = 7; // should be odd
// exists only while AppState is attached
private Node oceanNode;
private OceanSurface ocean;
public OceanAppState() {
super(UpdateInterval);
}
@Override
public void initialize(AppStateManager stateManager, Application baseApp) {
super.initialize(stateManager, baseApp);
ocean = new OceanSurface(GridSize, GridSize, GridStep, GridStep);
ocean.setAConstant(.001f);
ocean.setConvergenceConstant(.15f);
ocean.setWaveHeightScale(.1f);
ocean.setWindVelocity(new Vector3f(15,0,15));
ocean.setLambda(.05f);
ocean.initSim();
oceanNode = new Node("OceanNode");
oceanNode.setCullHint(CullHint.Never);
// Material oceanMat = new Material(getApp().getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md");
// oceanMat.setColor("Color", new ColorRGBA(0.5f, 0.5f, 1f, 1));
// oceanMat.getAdditionalRenderState().setWireframe(true);
// Material oceanMat = new Material(getApp().getAssetManager(), "Common/MatDefs/Misc/ShowNormals.j3md");
Material oceanMat = new Material(getApp().getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
oceanMat.setColor("Diffuse", new ColorRGBA(0.5f, 0.5f, 1f, 1));
oceanMat.setColor("Specular", ColorRGBA.White);
oceanMat.setBoolean("UseMaterialColors", true);
final int numGridTilesHalf = NumGridTiles/2;
for(int ix = -numGridTilesHalf; ix <= +numGridTilesHalf; ix++) {
for(int iz = -numGridTilesHalf; iz <= +numGridTilesHalf; iz++) {
Vector3f offset = new Vector3f(ix,0,iz);
offset.multLocal(GridStep);
oceanNode.attachChild(buildOceanTile(ocean, oceanMat, offset));
}
}
getApp().getRootNode().attachChild(oceanNode);
}
@Override
public void update(float dt) {
// we need the timed functionality too
super.update(dt);
ocean.update(dt);
TempVars vars = TempVars.get();
Vector3f loc = vars.vect1.set(getApp().getCamera().getLocation());
Vector3f gridLoc = vars.vect2.set(
MathExt.floor(loc.x/GridStep)*GridStep,
0,
MathExt.floor(loc.z/GridStep)*GridStep
);
oceanNode.setLocalTranslation(gridLoc);
vars.release();
}
@Override
protected void intervalUpdate() {
}
@Override
public void cleanup() {
super.cleanup();
getApp().getRootNode().detachChild(oceanNode);
ocean = null;
oceanNode = null;
}
private Geometry buildOceanTile(OceanSurface ocean, Material mat, Vector3f offset) {
Geometry geom = new Geometry("OceanSurface"+offset.toString(), ocean);
geom.setMaterial(mat);
geom.setLocalTranslation(offset);
geom.setLocalScale(1);
return geom;
}
} |
package org.griphyn.vdl.mapping;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.griphyn.vdl.karajan.Loader;
import org.griphyn.vdl.type.Types;
import org.griphyn.vdl.type.impl.FieldImpl;
public class ExternalDataNode extends AbstractDataNode {
static final String DATASET_URI_PREFIX = "dataset:external:";
public static final Logger logger = Logger.getLogger(ExternalDataNode.class);
public static final MappingParam PARAM_PREFIX = new MappingParam("prefix", null);
private static long datasetIDCounter = 850000000000l;
private static final String datasetIDPartialID = Loader.getUUID();
private Map<String, Object> params;
public ExternalDataNode() {
super(new FieldImpl("", Types.EXTERNAL));
}
@Override
public void init(Map<String, Object> params) {
this.params = params;
}
public boolean isRestartable() {
return true;
}
public DSHandle getRoot() {
return this;
}
public DSHandle getField(Path path) throws InvalidPathException {
if (path.isEmpty()) {
return this;
}
else {
throw new InvalidPathException(path, this);
}
}
protected void getFields(List<DSHandle> fields, Path path) throws InvalidPathException {
// nothing
}
public void set(DSHandle handle) {
throw new UnsupportedOperationException(this.getDisplayableName() + " is an external dataset and cannot be set");
}
public Object getValue() {
logger.warn("getValue called on an external dataset");
return null;
}
public Map<Comparable<?>, DSHandle> getArrayValue() {
throw new UnsupportedOperationException("cannot get value of external dataset");
}
public boolean isArray() {
return false;
}
public Collection<Path> getFringePaths() throws HandleOpenException {
return Collections.singletonList(Path.EMPTY_PATH);
}
public Path getPathFromRoot() {
return Path.EMPTY_PATH;
}
public Mapper getMapper() {
return null;
}
protected String makeIdentifierURIString() {
datasetIDCounter++;
return DATASET_URI_PREFIX + datasetIDPartialID + ":" + datasetIDCounter;
}
public DSHandle createDSHandle(String fieldName) {
throw new UnsupportedOperationException("cannot create new field in external dataset");
}
public DSHandle getParent() {
return null;
}
public String getParam(String name) {
if (params == null) {
return null;
}
return (String) params.get(name);
}
} |
package org.idlesoft.android.hubroid;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.idlesoft.libraries.ghapi.GitHubAPI;
import org.idlesoft.libraries.ghapi.Issues;
import org.idlesoft.libraries.ghapi.APIBase.Response;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SingleIssue extends Activity {
public ProgressDialog m_progressDialog;
public Intent m_intent;
private IssueCommentsAdapter m_adapter;
private JSONObject m_JSON = new JSONObject();
private SharedPreferences m_prefs;
private SharedPreferences.Editor m_editor;
private String m_repoOwner;
private String m_repoName;
private String m_username;
private String m_token;
private View m_header;
private View m_commentArea;
private View m_issueBox;
private Thread m_thread;
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu.hasVisibleItems()) menu.clear();
menu.add(0, 0, 0, "Back to Main").setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, 1, 0, "Clear Preferences");
menu.add(0, 2, 0, "Clear Cache");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Intent i1 = new Intent(this, Hubroid.class);
startActivity(i1);
return true;
case 1:
m_editor.clear().commit();
Intent intent = new Intent(this, Hubroid.class);
startActivity(intent);
return true;
case 2:
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File hubroid = new File(root, "hubroid");
if (!hubroid.exists() && !hubroid.isDirectory()) {
return true;
} else {
hubroid.delete();
return true;
}
}
}
return false;
}
private void loadIssueItemBox() {
TextView date = (TextView)m_header.findViewById(R.id.tv_issue_list_item_updated_date);
ImageView icon = (ImageView)m_header.findViewById(R.id.iv_issue_list_item_icon);
TextView title = (TextView)m_header.findViewById(R.id.tv_issue_list_item_title);
TextView number = (TextView)m_header.findViewById(R.id.tv_issue_list_item_number);
TextView topbar = (TextView)findViewById(R.id.tv_top_bar_title);
try {
String end;
SimpleDateFormat dateFormat = new SimpleDateFormat(Hubroid.GITHUB_ISSUES_TIME_FORMAT);
Date item_time = dateFormat.parse(m_JSON.getString("updated_at"));
Date current_time = dateFormat.parse(dateFormat.format(new Date()));
long ms = current_time.getTime() - item_time.getTime();
long sec = ms / 1000;
long min = sec / 60;
long hour = min / 60;
long day = hour / 24;
long year = day / 365;
if (year > 0) {
if (year == 1) {
end = " year ago";
} else {
end = " years ago";
}
date.setText("Updated " + year + end);
} else if (day > 0) {
if (day == 1) {
end = " day ago";
} else {
end = " days ago";
}
date.setText("Updated " + day + end);
} else if (hour > 0) {
if (hour == 1) {
end = " hour ago";
} else {
end = " hours ago";
}
date.setText("Updated " + hour + end);
} else if (min > 0) {
if (min == 1) {
end = " minute ago";
} else {
end = " minutes ago";
}
date.setText("Updated " + min + end);
} else {
if (sec == 1) {
end = " second ago";
} else {
end = " seconds ago";
}
date.setText("Updated " + sec + end);
}
if (m_JSON.getString("state").equalsIgnoreCase("open")) {
icon.setImageResource(R.drawable.issues_open);
} else {
icon.setImageResource(R.drawable.issues_closed);
}
number.setText("#" + m_JSON.getString("number"));
title.setText(m_JSON.getString("title"));
topbar.setText("Issue " + number.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.single_issue);
m_prefs = getSharedPreferences(Hubroid.PREFS_NAME, 0);
m_editor = m_prefs.edit();
m_username = m_prefs.getString("login", "");
m_token = m_prefs.getString("token", "");
final Bundle extras = getIntent().getExtras();
if (extras != null) {
try {
m_repoOwner = extras.getString("repoOwner");
m_repoName = extras.getString("repoName");
m_JSON = new JSONObject(extras.getString("item_json"));
m_issueBox = getLayoutInflater().inflate(R.layout.issue_list_item, null);
m_header = getLayoutInflater().inflate(R.layout.issue_header, null);
loadIssueItemBox();
((ListView)findViewById(R.id.lv_single_issue_comments)).addHeaderView(m_header);
((ImageView)m_header.findViewById(R.id.iv_single_issue_gravatar)).setImageBitmap(Hubroid.getGravatar(Hubroid.getGravatarID(m_JSON.getString("user")), 30));
((TextView)m_header.findViewById(R.id.tv_single_issue_body)).setText(m_JSON.getString("body").replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
String end;
SimpleDateFormat dateFormat = new SimpleDateFormat(Hubroid.GITHUB_ISSUES_TIME_FORMAT);
Date item_time = dateFormat.parse(m_JSON.getString("created_at"));
Date current_time = dateFormat.parse(dateFormat.format(new Date()));
long ms = current_time.getTime() - item_time.getTime();
long sec = ms / 1000;
long min = sec / 60;
long hour = min / 60;
long day = hour / 24;
long year = day / 365;
if (year > 0) {
if (year == 1) {
end = " year ago";
} else {
end = " years ago";
}
((TextView)m_header.findViewById(R.id.tv_single_issue_meta)).setText("Posted " + year + end + " by " + m_JSON.getString("user"));
}
if (day > 0) {
if (day == 1) {
end = " day ago";
} else {
end = " days ago";
}
((TextView)m_header.findViewById(R.id.tv_single_issue_meta)).setText("Posted " + day + end + " by " + m_JSON.getString("user"));
} else if (hour > 0) {
if (hour == 1) {
end = " hour ago";
} else {
end = " hours ago";
}
((TextView)m_header.findViewById(R.id.tv_single_issue_meta)).setText("Posted " + hour + end + " by " + m_JSON.getString("user"));
} else if (min > 0) {
if (min == 1) {
end = " minute ago";
} else {
end = " minutes ago";
}
((TextView)m_header.findViewById(R.id.tv_single_issue_meta)).setText("Posted " + min + end + " by " + m_JSON.getString("user"));
} else {
if (sec == 1) {
end = " second ago";
} else {
end = " seconds ago";
}
((TextView)m_header.findViewById(R.id.tv_single_issue_meta)).setText("Posted " + sec + end + " by " + m_JSON.getString("user"));
}
m_commentArea = getLayoutInflater().inflate(R.layout.issue_comment_area, null);
((ListView)findViewById(R.id.lv_single_issue_comments)).addFooterView(m_commentArea);
((Button)m_commentArea.findViewById(R.id.btn_issue_comment_area_submit)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String comment_body = ((TextView)m_commentArea.findViewById(R.id.et_issue_comment_area_body)).getText().toString();
if (!comment_body.equals("")) {
((ProgressBar)m_commentArea.findViewById(R.id.pb_issue_comment_area_progress)).setVisibility(View.VISIBLE);
m_thread = new Thread(new Runnable() {
public void run() {
try {
if (Issues.add_comment(m_repoOwner, m_repoName, m_JSON.getInt("number"), ((TextView)m_commentArea.findViewById(R.id.et_issue_comment_area_body)).getText().toString(), m_username, m_token).statusCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
((ProgressBar)m_commentArea.findViewById(R.id.pb_issue_comment_area_progress)).setVisibility(View.GONE);
m_progressDialog = ProgressDialog.show(SingleIssue.this, "Please wait...", "Refreshing Comments...", true);
}
});
Response response = Issues.list_comments(m_repoOwner, m_repoName, m_JSON.getInt("number"), m_username, m_token);
m_adapter = new IssueCommentsAdapter(getApplicationContext(), new JSONObject(response.resp).getJSONArray("comments"));
runOnUiThread(new Runnable() {
public void run() {
((TextView)m_commentArea.findViewById(R.id.et_issue_comment_area_body)).setText("");
((ListView)findViewById(R.id.lv_single_issue_comments)).setAdapter(m_adapter);
m_progressDialog.dismiss();
}
});
} else {
Toast.makeText(getApplicationContext(), "Error posting comment.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
m_thread.start();
}
}
});
m_thread = new Thread(new Runnable() {
public void run() {
try {
Response response = Issues.list_comments(m_repoOwner, m_repoName, m_JSON.getInt("number"), m_username, m_token);
m_adapter = new IssueCommentsAdapter(getApplicationContext(), new JSONObject(response.resp).getJSONArray("comments"));
runOnUiThread(new Runnable() {
public void run() {
((ListView)findViewById(R.id.lv_single_issue_comments)).setAdapter(m_adapter);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
m_thread.start();
} catch (JSONException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
}
}
@Override
public void onPause()
{
if (m_thread != null && m_thread.isAlive())
m_thread.stop();
if (m_progressDialog != null && m_progressDialog.isShowing())
m_progressDialog.dismiss();
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("commentText", ((EditText)m_commentArea.findViewById(R.id.et_issue_comment_area_body)).getText().toString());
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("commentText")) {
((EditText)m_commentArea.findViewById(R.id.et_issue_comment_area_body)).setText(savedInstanceState.getString("commentText"));
}
}
} |
package org.nees.buffalo.rdv.rbnb;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nees.buffalo.rdv.DataViewer;
import com.rbnb.sapi.ChannelMap;
import com.rbnb.sapi.ChannelTree;
import com.rbnb.sapi.SAPIException;
import com.rbnb.sapi.Sink;
/**
* A class to manage a connection to an RBNB server and to post channel data to
* interested listeners.
*
* @author Jason P. Hanley
*/
public class RBNBController implements Player, MetadataListener {
static Log log = LogFactory.getLog(RBNBController.class.getName());
/** the single instance of this class */
protected static RBNBController instance;
private String rbnbSinkName = "RDV";
private Thread rbnbThread;
private int state;
private Sink sink;
private String rbnbHostName;
private int rbnbPortNumber;
private static final String DEFAULT_RBNB_HOST_NAME = "localhost";
private static final int DEFAULT_RBNB_PORT_NUMBER = 3333;
private boolean requestIsMonitor;
private ChannelMap requestedChannels;
private ChannelTree metaDataChannelTree;
private ChannelManager channelManager;
private MetadataManager metadataManager;
private MarkerManager markerManager;
private Vector timeListeners;
private Vector stateListeners;
private Vector subscriptionListeners;
private ArrayList playbackRateListeners;
private ArrayList timeScaleChangeListeners;
private ArrayList messageListeners;
private ArrayList connectionListeners;
private ChannelMap preFetchChannelMap;
private Object preFetchLock = new Object();
private boolean preFetchDone;
private double location;
private double playbackRate;
private double timeScale;
private double updateLocation = -1;
private Object updateLocationLock = new Object();
private double updateTimeScale = -1;
private Object updateTimeScaleLock = new Object();
private double updatePlaybackRate = -1;
private Object updatePlaybackRateLock = new Object();
private ArrayList stateChangeRequests = new ArrayList();
private ArrayList updateSubscriptionRequests = new ArrayList();
private boolean dropData;
private final double PLAYBACK_REFRESH_RATE = 0.05;
private final long LOADING_TIMEOUT = 30000;
protected RBNBController() {
// get the system host name and append it to the sink name
try {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
rbnbSinkName += "@" + hostname;
} catch (UnknownHostException e) {}
state = STATE_DISCONNECTED;
rbnbHostName = DEFAULT_RBNB_HOST_NAME;
rbnbPortNumber = DEFAULT_RBNB_PORT_NUMBER;
requestIsMonitor = false;
dropData = true;
location = System.currentTimeMillis()/1000d;
playbackRate = 1;
timeScale = 1;
requestedChannels = new ChannelMap();
metaDataChannelTree = ChannelTree.EMPTY_TREE;
channelManager = new ChannelManager();
metadataManager = new MetadataManager(this);
markerManager = new MarkerManager(this);
timeListeners = new Vector();
stateListeners = new Vector();
subscriptionListeners = new Vector();
playbackRateListeners = new ArrayList();
timeScaleChangeListeners = new ArrayList();
messageListeners = new ArrayList();
connectionListeners = new ArrayList();
run();
}
/**
* Get the single instance of this class.
*
* @return the instance of this class
*/
public static RBNBController getInstance() {
if (instance == null) {
instance = new RBNBController();
}
return instance;
}
private void run() {
rbnbThread = new Thread(new Runnable() {
public void run() {
runRBNB();
}
}, "RBNB");
rbnbThread.start();
}
private void runRBNB() {
log.info("RBNB data thread has started.");
while (state != STATE_EXITING) {
processSubscriptionRequests();
processLocationUpdate();
processTimeScaleUpdate();
processPlaybackRateUpdate();
processStateChangeRequests();
switch (state) {
case STATE_LOADING:
log.warn("You must always manually transition from the loading state.");
changeStateSafe(STATE_STOPPED);
break;
case STATE_PLAYING:
updateDataPlaying();
break;
case STATE_MONITORING:
updateDataMonitoring();
break;
case STATE_STOPPED:
case STATE_DISCONNECTED:
try { Thread.sleep(50); } catch (Exception e) {}
break;
}
}
closeRBNB();
metadataManager.stopUpdating();
log.info("RBNB data thread is exiting.");
}
// State Processing Methods
private void processSubscriptionRequests() {
while (!updateSubscriptionRequests.isEmpty()) {
SubscriptionRequest subscriptionRequest;
synchronized (updateSubscriptionRequests) {
subscriptionRequest = (SubscriptionRequest)updateSubscriptionRequests.remove(0);
}
String channelName = subscriptionRequest.getChannelName();
DataListener listener = subscriptionRequest.getListener();
if (subscriptionRequest.isSubscribe()) {
subscribeSafe(channelName, listener);
} else {
unsubscribeSafe(channelName, listener);
}
}
}
private void processLocationUpdate() {
if (updateLocation != -1) {
double oldLocation = location;
synchronized (updateLocationLock) {
location = updateLocation;
updateLocation = -1;
}
if (oldLocation == location) {
return;
}
log.info("Setting location to " + DataViewer.formatDate(location) + ".");
if (requestedChannels.NumberOfChannels() > 0) {
changeStateSafe(STATE_LOADING);
double duration;
if (oldLocation < location && oldLocation > location-timeScale) {
duration = location - oldLocation;
} else {
duration = timeScale;
}
loadData(location, duration);
changeStateSafe(STATE_STOPPED);
} else {
updateTimeListeners(location);
}
}
}
private void processTimeScaleUpdate() {
if (updateTimeScale != -1) {
double oldTimeScale = timeScale;
synchronized (updateTimeScaleLock) {
timeScale = updateTimeScale;
updateTimeScale = -1;
}
if (timeScale == oldTimeScale) {
return;
}
log.info("Setting time scale to " + timeScale + ".");
fireTimeScaleChanged(timeScale);
if (timeScale > oldTimeScale && requestedChannels.NumberOfChannels() > 0) {
//TODO make this loading smarter
int originalState = state;
changeStateSafe(STATE_LOADING);
loadData();
if (originalState == STATE_PLAYING) {
changeStateSafe(STATE_PLAYING);
} else if (originalState == STATE_MONITORING) {
changeStateSafe(STATE_MONITORING);
} else {
changeStateSafe(STATE_STOPPED);
}
}
}
}
private void processPlaybackRateUpdate() {
if (updatePlaybackRate != -1) {
double oldPlaybackRate = playbackRate;
synchronized (updatePlaybackRateLock) {
playbackRate = updatePlaybackRate;
updatePlaybackRate = -1;
}
if (playbackRate == oldPlaybackRate) {
return;
}
log.info("Setting playback rate to " + playbackRate + " seconds.");
if (state == STATE_PLAYING) {
getPreFetchChannelMap();
preFetchData(location, playbackRate);
}
firePlaybackRateChanged(playbackRate);
}
}
private void processStateChangeRequests() {
while (!stateChangeRequests.isEmpty()) {
int updateState;
synchronized (stateChangeRequests) {
updateState = ((Integer)stateChangeRequests.remove(0)).intValue();
}
changeStateSafe(updateState);
}
}
private boolean changeStateSafe(int newState) {
if (state == newState) {
log.info("Already in state " + getStateName(state) + ".");
return true;
} else if (state == STATE_PLAYING) {
getPreFetchChannelMap();
} else if (state == STATE_EXITING) {
log.error("Can not transition out of exiting state to " + getStateName(state) + " state.");
return false;
} else if (state == STATE_DISCONNECTED && newState != STATE_EXITING) {
fireConnecting();
try {
initRBNB();
} catch (SAPIException e) {
closeRBNB();
String message = e.getMessage();
// detect nested excpetions
if (message.contains("java.io.InterruptedIOException")) {
log.info("RBNB server connection canceled by user.");
} else {
log.error("Failed to connect to the RBNB server.");
fireErrorMessage("Failed to connect to the RBNB server.");
}
fireConnectionFailed();
return false;
}
metadataManager.startUpdating();
fireConnected();
}
switch (newState) {
case STATE_MONITORING:
if (!monitorData()) {
fireErrorMessage("Stopping real time. Failed to load data from the server. Please try again later.");
return false;
}
break;
case STATE_PLAYING:
preFetchData(location, playbackRate);
break;
case STATE_LOADING:
case STATE_STOPPED:
case STATE_EXITING:
break;
case STATE_DISCONNECTED:
closeRBNB();
metadataManager.stopUpdating();
break;
default:
log.error("Unknown state: " + state + ".");
return false;
}
int oldState = state;
state = newState;
notifyStateListeners(state, oldState);
log.info("Transitioned from state " + getStateName(oldState) + " to " + getStateName(state) + ".");
return true;
}
// RBNB Methods
private void initRBNB() throws SAPIException {
if (sink == null) {
sink = new Sink();
} else {
return;
}
sink.OpenRBNBConnection(rbnbHostName + ":" + rbnbPortNumber, rbnbSinkName);
log.info("Connected to RBNB server.");
}
private void closeRBNB() {
if (sink == null) return;
sink.CloseRBNBConnection();
sink = null;
log.info("Connection to RBNB server closed.");
}
private void reInitRBNB() throws SAPIException {
closeRBNB();
initRBNB();
}
// Subscription Methods
private boolean subscribeSafe(String channelName, DataListener panel) {
//skip subscription if we are not connected
if (state == STATE_DISCONNECTED) {
return false;
}
//subscribe to channel
try {
requestedChannels.Add(channelName);
} catch (SAPIException e) {
log.error("Failed to add channel " + channelName + ".");
e.printStackTrace();
return false;
}
//notify channel manager
channelManager.subscribe(channelName, panel);
int originalState = state;
changeStateSafe(STATE_LOADING);
loadData(channelName);
if (originalState == STATE_MONITORING) {
changeStateSafe(STATE_MONITORING);
} else if (originalState == STATE_PLAYING) {
changeStateSafe(STATE_PLAYING);
} else {
changeStateSafe(STATE_STOPPED);
}
fireSubscriptionNotification(channelName);
return true;
}
private boolean unsubscribeSafe(String channelName, DataListener panel) {
//skip unsubscription if we are not connected
if (state == STATE_DISCONNECTED) {
return false;
}
channelManager.unsubscribe(channelName, panel);
if (!channelManager.isChannelSubscribed(channelName)) {
//unsubscribe from the channel
ChannelMap newRequestedChannels = new ChannelMap();
String[] channelList = requestedChannels.GetChannelList();
for (int i=0; i<channelList.length; i++) {
if (!channelName.equals(channelList[i])) {
try {
newRequestedChannels.Add(channelList[i]);
} catch (SAPIException e) {
log.error("Failed to remove to channel " + channelName + ".");
e.printStackTrace();
return false;
}
}
}
requestedChannels = newRequestedChannels;
}
log.info("Unsubscribed from " + channelName + " for listener " + panel + ".");
if (state == STATE_MONITORING) {
monitorData();
}
fireUnsubscriptionNotification(channelName);
return true;
}
// Load Methods
/**
* Load data for all channels.
*/
private void loadData() {
loadData(location, timeScale);
}
/**
* Load data for all channels.
*
* @param location the end time
* @param duration the duration
*/
private void loadData(double location, double duration) {
String[] subscribedChannels = requestedChannels.GetChannelList();
loadData(Arrays.asList(subscribedChannels), location, duration);
}
/**
* Load data for the specified channel.
*
* @param channelName the name of the channel
*/
private void loadData(String channelName) {
loadData(Collections.singletonList(channelName), location, timeScale);
}
/**
* Load data for the specified channels.
*
* @param channelNames a list of channel names
* @param location the end time
* @param duration the amount of data to load
*/
private void loadData(List<String> channelNames, double location, double duration) {
ChannelMap realRequestedChannels = requestedChannels;
ChannelMap imageChannels = new ChannelMap();
ChannelMap tabularChannels = new ChannelMap();
ChannelMap otherChannels = new ChannelMap();
for (String channelName : channelNames) {
try {
if (isVideo(metaDataChannelTree, channelName)) {
imageChannels.Add(channelName);
} else if (channelManager.isChannelTabularOnly(channelName)) {
tabularChannels.Add(channelName);
} else {
otherChannels.Add(channelName);
}
} catch (SAPIException e) {
log.error("Failed to add channel " + channelName + ".");
e.printStackTrace();
}
}
if (imageChannels.NumberOfChannels() > 0) {
requestedChannels = imageChannels;
if (!requestData(location, 0)) {
fireErrorMessage("Failed to load data from the server. Please try again later.");
requestedChannels = realRequestedChannels;
changeStateSafe(STATE_STOPPED);
return;
}
updateDataMonitoring();
updateTimeListeners(location);
}
if (tabularChannels.NumberOfChannels() > 0) {
requestedChannels = tabularChannels;
if (!requestData(location-1, 1)) {
fireErrorMessage("Failed to load data from the server. Please try again later.");
requestedChannels = realRequestedChannels;
changeStateSafe(STATE_STOPPED);
return;
}
updateDataMonitoring();
updateTimeListeners(location);
}
if (otherChannels.NumberOfChannels() > 0) {
requestedChannels = otherChannels;
if (!requestData(location-duration, duration)) {
fireErrorMessage("Failed to load data from the server. Please try again later.");
requestedChannels = realRequestedChannels;
changeStateSafe(STATE_STOPPED);
return;
}
updateDataMonitoring();
updateTimeListeners(location);
}
requestedChannels = realRequestedChannels;
log.info("Loaded " + DataViewer.formatSeconds(timeScale) + " of data at " + DataViewer.formatDate(location) + ".");
}
// Playback Methods
private boolean requestData(double location, double duration) {
return requestData(location, duration, true);
}
private boolean requestData(double location, double duration, boolean retry) {
if (requestedChannels.NumberOfChannels() == 0) {
return false;
}
if (requestIsMonitor) {
try {
reInitRBNB();
} catch (SAPIException e) {
requestIsMonitor = true;
return false;
}
requestIsMonitor = false;
}
try {
sink.Request(requestedChannels, location, duration, "absolute");
} catch (SAPIException e) {
log.error("Failed to request channels at " + DataViewer.formatDate(location) + " for " + DataViewer.formatSeconds(duration) + ".");
e.printStackTrace();
requestIsMonitor = true;
if (retry) {
return requestData(location, duration, false);
} else {
return false;
}
}
return true;
}
private synchronized void updateDataPlaying() {
if (requestedChannels.NumberOfChannels() == 0) {
fireStatusMessage("Stopping playback. No channels are selected.");
changeStateSafe(STATE_STOPPED);
return;
}
ChannelMap getmap = null;
getmap = getPreFetchChannelMap();
if (getmap == null) {
fireErrorMessage("Stopping playback. Failed to load data from the server. Please try again later.");
changeStateSafe(STATE_STOPPED);
requestIsMonitor = true;
return;
} else if (getmap.GetIfFetchTimedOut()) {
fireErrorMessage("Stopping playback. Failed to load enough data from server. The playback rate may be too fast or the server is busy.");
changeStateSafe(STATE_STOPPED);
return;
}
//stop if no data in fetch and past end time, most likely end of data
if (getmap.NumberOfChannels() == 0 && !moreData(requestedChannels.GetChannelList(), metaDataChannelTree, location)) {
log.warn("Received no data. Assuming end of channel.");
changeStateSafe(STATE_STOPPED);
return;
}
preFetchData(location+playbackRate, playbackRate);
channelManager.postData(getmap);
double playbackDuration = playbackRate;
double playbackRefreshRate = PLAYBACK_REFRESH_RATE;
double playbackStepTime = playbackRate * playbackRefreshRate;
long playbackSteps = (long)(playbackDuration / playbackStepTime);
double locationStartTime = location;
long playbackStartTime = System.nanoTime();
long i = 0;
while (i<playbackSteps && stateChangeRequests.size() == 0 && updateLocation == -1 && updateTimeScale == -1 && updatePlaybackRate == -1) {
double timeDifference = (playbackRefreshRate*(i+1)) - ((System.nanoTime() - playbackStartTime)/1000000000d);
if (dropData && timeDifference < -playbackRefreshRate) {
int stepsToSkip = (int)((timeDifference*-1) / playbackRefreshRate);
i += stepsToSkip;
} else if (timeDifference > playbackRefreshRate) {
try { Thread.sleep((long)(timeDifference*1000)); } catch (Exception e) { e.printStackTrace(); }
}
i++;
location = locationStartTime + (playbackStepTime) * i;
updateTimeListeners(location);
}
}
private void preFetchData(final double location, final double duration) {
preFetchChannelMap = null;
preFetchDone = false;
new Thread(new Runnable() {
public void run() {
boolean requestStatus = false;
if (state == STATE_PLAYING) {
requestStatus = requestData(location, duration);
}
if (requestStatus) {
try {
preFetchChannelMap = sink.Fetch(LOADING_TIMEOUT);
} catch (Exception e) {
log.error("Failed to fetch data.");
e.printStackTrace();
}
} else {
preFetchChannelMap = null;
}
synchronized(preFetchLock) {
preFetchDone = true;
preFetchLock.notify();
}
}
}, "prefetch").start();
}
private ChannelMap getPreFetchChannelMap() {
synchronized(preFetchLock) {
if (!preFetchDone) {
log.debug("Waiting for pre-fetch channel map.");
try {
preFetchLock.wait();
} catch (Exception e) {
log.error("Failed to wait for channel map.");
e.printStackTrace();
}
log.debug("Done waiting for pre-fetch channel map.");
}
}
ChannelMap fetchedMap = preFetchChannelMap;
preFetchChannelMap = null;
return fetchedMap;
}
// Monitor Methods
private boolean monitorData() {
return monitorData(true);
}
private boolean monitorData(boolean retry) {
if (requestedChannels.NumberOfChannels() == 0) {
return true;
}
if (requestIsMonitor) {
try {
reInitRBNB();
} catch (SAPIException e) {
e.printStackTrace();
return false;
}
}
log.debug("Monitoring data after location " + DataViewer.formatDate(location) + ".");
requestIsMonitor = true;
try {
sink.Monitor(requestedChannels, 5);
log.info("Monitoring selected data channels.");
} catch (SAPIException e) {
log.error("Failed to monitor channels.");
e.printStackTrace();
if (retry) {
return monitorData(false);
} else {
return false;
}
}
return true;
}
private void updateDataMonitoring() {
//stop monitoring if no channels selected
if (requestedChannels.NumberOfChannels() == 0) {
fireStatusMessage("Stopping real time. No channels are selected.");
changeStateSafe(STATE_STOPPED);
return;
}
ChannelMap getmap = null;
long timeout;
if (state == STATE_MONITORING) {
timeout = 500;
} else {
timeout = LOADING_TIMEOUT;
}
try {
getmap = sink.Fetch(timeout);
} catch (Exception e) {
fireErrorMessage("Failed to load data from the server. Please try again later.");
e.printStackTrace();
changeStateSafe(STATE_STOPPED);
requestIsMonitor = true;
return;
}
if (getmap.GetIfFetchTimedOut()) {
if (state == STATE_MONITORING) {
//no data was received, this is not an error and we should go on
//to see if more data is recieved next time around
//TODO see if we should sleep here
log.debug("Fetch timed out for monitor.");
return;
} else {
log.error("Failed to fetch data.");
fireErrorMessage("Failed to load data from the server. Please try again later.");
changeStateSafe(STATE_STOPPED);
return;
}
}
//received no data
if (getmap.NumberOfChannels() == 0) {
return;
}
//post data to listeners
channelManager.postData(getmap);
if (state == STATE_MONITORING) {
//update current location
double newLocation = getLastTime(getmap);
if (newLocation > location) {
location = newLocation;
}
updateTimeListeners(location);
}
}
// Listener Methods
private void updateTimeListeners(double location) {
for (int i=0; i<timeListeners.size(); i++) {
TimeListener timeListener = (TimeListener)timeListeners.get(i);
try {
timeListener.postTime(location);
} catch (Exception e) {
log.error("Failed to post time to " + timeListener + ".");
e.printStackTrace();
}
}
}
private void notifyStateListeners(int state, int oldState) {
for (int i=0; i<stateListeners.size(); i++) {
StateListener stateListener = (StateListener)stateListeners.get(i);
stateListener.postState(state, oldState);
}
}
private void fireSubscriptionNotification(String channelName) {
SubscriptionListener subscriptionListener;
for (int i=0; i<subscriptionListeners.size(); i++) {
subscriptionListener = (SubscriptionListener)subscriptionListeners.get(i);
subscriptionListener.channelSubscribed(channelName);
}
}
private void fireUnsubscriptionNotification(String channelName) {
SubscriptionListener subscriptionListener;
for (int i=0; i<subscriptionListeners.size(); i++) {
subscriptionListener = (SubscriptionListener)subscriptionListeners.get(i);
subscriptionListener.channelUnsubscribed(channelName);
}
}
private void firePlaybackRateChanged(double playbackRate) {
PlaybackRateListener listener;
for (int i=0; i<playbackRateListeners.size(); i++) {
listener = (PlaybackRateListener)playbackRateListeners.get(i);
listener.playbackRateChanged(playbackRate);
}
}
private void fireTimeScaleChanged(double timeScale) {
TimeScaleListener listener;
for (int i=0; i<timeScaleChangeListeners.size(); i++) {
listener = (TimeScaleListener)timeScaleChangeListeners.get(i);
listener.timeScaleChanged(timeScale);
}
}
// Utility (Static) Methods
private static boolean moreData(String[] channels, ChannelTree ctree, double time) {
double endTime = -1;
Iterator it = ctree.iterator();
while (it.hasNext()) {
ChannelTree.Node node = (ChannelTree.Node)it.next();
double channelEndTime = node.getStart() + node.getDuration();
if (channelEndTime != -1) {
endTime = Math.max(endTime, channelEndTime);
}
}
if (endTime == -1 || time >= endTime) {
return false;
} else {
return true;
}
}
private static boolean isVideo(ChannelTree channelTree, String channelName) {
if (channelName == null) {
log.error("Channel name is null for. Can't determine if is video.");
return false;
} else if (channelTree == null) {
log.warn("Haven't received metadata yet, can't determine channel type.");
return false;
}
ChannelTree.Node node = channelTree.findNode(channelName);
if (node == null) {
log.error("Unable to find channel in metadata.");
return false;
} else {
String mime = node.getMime();
if (mime != null && mime.equals("image/jpeg")) {
return true;
} else if (channelName.endsWith(".jpg")){
return true;
} else {
return false;
}
}
}
private static double getLastTime(ChannelMap channelMap) {
double lastTime = -1;
String[] channels = channelMap.GetChannelList();
for (int i=0; i<channels.length; i++) {
String channelName = channels[i];
int channelIndex = channelMap.GetIndex(channelName);
double[] times = channelMap.GetTimes(channelIndex);
double endTime = times[times.length-1];
if (endTime > lastTime) {
lastTime = endTime;
}
}
return lastTime;
}
// Player Methods
public int getState() {
return state;
}
public void monitor() {
if (state != STATE_MONITORING) {
setLocation(System.currentTimeMillis()/1000d);
}
setState(STATE_MONITORING);
}
public void play() {
setState(STATE_PLAYING);
}
public void pause() {
setState(STATE_STOPPED);
}
public void exit() {
setState(STATE_EXITING);
//wait for thread to finish
int count = 0;
while (sink != null && count++ < 20) {
try { Thread.sleep(50); } catch (Exception e) {}
}
}
public void setState(int state) {
synchronized (stateChangeRequests) {
stateChangeRequests.add(new Integer(state));
}
}
public double getLocation() {
return location;
}
public void setLocation(final double location) {
if (location < 0) {
log.error("Location not set; location must be nonnegative.");
return;
}
synchronized (updateLocationLock) {
updateLocation = location;
}
}
public double getPlaybackRate() {
return playbackRate;
}
public void setPlaybackRate(final double playbackRate) {
if (playbackRate <= 0) {
log.error("Playback rate not set; playback rate must be positive.");
return;
}
synchronized (updatePlaybackRateLock) {
updatePlaybackRate = playbackRate;
}
}
public double getTimeScale() {
return timeScale;
}
public void setTimeScale(double timeScale) {
if (timeScale <= 0) {
log.error("Time scale not set; time scale must be positive.");
return;
}
synchronized (updateTimeScaleLock) {
updateTimeScale = timeScale;
}
}
public boolean subscribe(String channelName, DataListener listener) {
synchronized (updateSubscriptionRequests) {
updateSubscriptionRequests.add(new SubscriptionRequest(channelName, listener, true));
}
return true;
}
public boolean unsubscribe(String channelName, DataListener listener) {
synchronized (updateSubscriptionRequests) {
updateSubscriptionRequests.add(new SubscriptionRequest(channelName, listener, false));
}
return true;
}
public boolean isSubscribed(String channelName) {
return channelManager.isChannelSubscribed(channelName);
}
/**
* Returns true if there is at least one listener subscribed to a channel.
*
* @return true if there are channel listener, false if there are none
*/
public boolean hasSubscribedChannels() {
return channelManager.hasSubscribedChannels();
}
public void addStateListener(StateListener stateListener) {
stateListener.postState(state, state);
stateListeners.add(stateListener);
}
public void removeStateListener(StateListener stateListener) {
stateListeners.remove(stateListener);
}
public void addTimeListener(TimeListener timeListener) {
timeListeners.add(timeListener);
timeListener.postTime(location);
}
public void removeTimeListener(TimeListener timeListener) {
timeListeners.remove(timeListener);
}
public void addPlaybackRateListener(PlaybackRateListener listener) {
listener.playbackRateChanged(playbackRate);
playbackRateListeners.add(listener);
}
public void removePlaybackRateListener(PlaybackRateListener listener) {
playbackRateListeners.remove(listener);
}
public void addTimeScaleListener(TimeScaleListener listener) {
listener.timeScaleChanged(timeScale);
timeScaleChangeListeners.add(listener);
}
public void removeTimeScaleListener(TimeScaleListener listener) {
timeScaleChangeListeners.remove(listener);
}
// Public Methods
public void dropData(boolean dropData) {
this.dropData = dropData;
}
public String getRBNBHostName() {
return rbnbHostName;
}
public void setRBNBHostName(String rbnbHostName) {
this.rbnbHostName = rbnbHostName;
}
public int getRBNBPortNumber() {
return rbnbPortNumber;
}
public void setRBNBPortNumber(int rbnbPortNumber) {
this.rbnbPortNumber = rbnbPortNumber;
}
public String getRBNBConnectionString() {
return rbnbHostName + ":" + rbnbPortNumber;
}
/**
* Gets the name of the server. If there is no active connection, null is
* returned.
*
* @return the name of the server, or null if there is no connection
*/
public String getServerName() {
if (sink == null) {
return null;
}
String serverName;
try {
serverName = sink.GetServerName();
// strip out the leading slash that is there for some reason
if (serverName.startsWith("/") && serverName.length() >= 2) {
serverName = serverName.substring(1);
}
} catch (IllegalStateException e) {
serverName = null;
}
return serverName;
}
public boolean isConnected() {
return sink != null;
}
public void connect() {
connect(false);
}
public boolean connect(boolean block) {
if (isConnected()) {
return true;
}
if (block) {
final Thread object = Thread.currentThread();
ConnectionListener listener = new ConnectionListener() {
public void connecting() {}
public void connected() {
synchronized (object) {
object.notify();
}
}
public void connectionFailed() {
object.interrupt();
}
};
addConnectionListener(listener);
synchronized (object) {
setState(STATE_STOPPED);
try {
object.wait();
} catch (InterruptedException e) {
return false;
}
}
removeConnectionListener(listener);
} else {
setState(STATE_STOPPED);
}
return true;
}
/**
* Cancel a connection attempt.
*/
public void cancelConnect() {
if (rbnbThread != null) {
rbnbThread.interrupt();
}
}
/**
* Disconnect from the RBNB server. This method will return immediately.
*/
public void disconnect() {
disconnect(false);
}
/**
* Disconnect from the RBNB server. If block is set, this method will not
* return until the server has disconnected.
*
* @param block if true, wait for the server to disconnect
* @return true if the server disconnected
*/
public boolean disconnect(boolean block) {
if (!isConnected()) {
return true;
}
if (block) {
final Thread object = Thread.currentThread();
StateListener listener = new StateListener() {
public void postState(int newState, int oldState) {
if (newState == STATE_DISCONNECTED) {
synchronized (object) {
object.notify();
}
}
}
};
addStateListener(listener);
synchronized (object) {
setState(STATE_DISCONNECTED);
try {
object.wait();
} catch (InterruptedException e) {
return false;
}
}
removeStateListener(listener);
} else {
setState(STATE_DISCONNECTED);
}
return true;
}
public void reconnect() {
setState(STATE_DISCONNECTED);
setState(STATE_STOPPED);
}
public void addSubscriptionListener(SubscriptionListener subscriptionListener) {
subscriptionListeners.add(subscriptionListener);
}
public void removeSubscriptionListener(SubscriptionListener subscriptionListener) {
subscriptionListeners.remove(subscriptionListener);
}
//Message Methods
private void fireErrorMessage(String errorMessage) {
for (int i=0; i<messageListeners.size(); i++) {
MessageListener messageListener = (MessageListener)messageListeners.get(i);
messageListener.postError(errorMessage);
}
}
private void fireStatusMessage(String statusMessage) {
for (int i=0; i<messageListeners.size(); i++) {
MessageListener messageListener = (MessageListener)messageListeners.get(i);
messageListener.postStatus(statusMessage);
}
}
public void addMessageListener(MessageListener messageListener) {
messageListeners.add(messageListener);
}
public void removeMessageListener(MessageListener messageListener) {
messageListeners.remove(messageListener);
}
// Connection Listener Methods
private void fireConnecting() {
for (int i=0; i<connectionListeners.size(); i++) {
ConnectionListener connectionListener = (ConnectionListener)connectionListeners.get(i);
connectionListener.connecting();
}
}
private void fireConnected() {
for (int i=0; i<connectionListeners.size(); i++) {
ConnectionListener connectionListener = (ConnectionListener)connectionListeners.get(i);
connectionListener.connected();
}
}
private void fireConnectionFailed() {
for (int i=0; i<connectionListeners.size(); i++) {
ConnectionListener connectionListener = (ConnectionListener)connectionListeners.get(i);
connectionListener.connectionFailed();
}
}
public void addConnectionListener(ConnectionListener connectionListener) {
connectionListeners.add(connectionListener);
}
public void removeConnectionListener(ConnectionListener connectionListener) {
connectionListeners.remove(connectionListener);
}
//Public Metadata Methods
public MetadataManager getMetadataManager() {
return metadataManager;
}
public Channel getChannel(String channelName) {
return metadataManager.getChannel(channelName);
}
public void updateMetadata() {
metadataManager.updateMetadataBackground();
}
public void channelTreeUpdated(ChannelTree ctree) {
metaDataChannelTree = ctree;
}
//Public Marker Methods
public MarkerManager getMarkerManager() {
return markerManager;
}
//Public Static Methods
public static String getStateName(int state) {
String stateString;
switch (state) {
case STATE_LOADING:
stateString = "loading";
break;
case STATE_PLAYING:
stateString = "playing";
break;
case STATE_MONITORING:
stateString = "real time";
break;
case STATE_STOPPED:
stateString = "stopped";
break;
case STATE_EXITING:
stateString = "exiting";
break;
case STATE_DISCONNECTED:
stateString = "disconnected";
break;
default:
stateString = "UNKNOWN";
}
return stateString;
}
/**
* Returns the state code for a given state name
*
* @param stateName the state name
* @return the state code
*/
public static int getState(String stateName) {
int code;
if (stateName.equals("loading")) {
code = STATE_LOADING;
} else if (stateName.equals("playing")) {
code = STATE_PLAYING;
} else if (stateName.equals("real time")) {
code = STATE_MONITORING;
} else if (stateName.equals("stopped")) {
code = STATE_STOPPED;
} else if (stateName.equals("exiting")) {
code = STATE_EXITING;
} else if (stateName.equals("disconnected")) {
code = STATE_DISCONNECTED;
} else {
code = -1;
}
return code;
}
class SubscriptionRequest {
private String channelName;
private DataListener listener;
private boolean isSubscribe;
public SubscriptionRequest(String channelName, DataListener listener, boolean isSubscribe) {
this.channelName = channelName;
this.listener = listener;
this.isSubscribe = isSubscribe;
}
public String getChannelName() {
return channelName;
}
public DataListener getListener() {
return listener;
}
public boolean isSubscribe() {
return isSubscribe;
}
}
} |
package org.nees.buffalo.rdv.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
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.JRadioButtonMenuItem;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.xml.transform.TransformerException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nees.buffalo.rdv.DataPanelManager;
import org.nees.buffalo.rdv.DataViewer;
import org.nees.buffalo.rdv.Extension;
import org.nees.buffalo.rdv.rbnb.ConnectionListener;
import org.nees.buffalo.rdv.rbnb.MessageListener;
import org.nees.buffalo.rdv.rbnb.Player;
import org.nees.buffalo.rdv.rbnb.RBNBController;
import org.nees.buffalo.rdv.rbnb.RBNBUtilities;
import org.nees.buffalo.rdv.rbnb.StateListener;
import org.nees.rbnb.marker.SendMarkerRDVPanel;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import com.jgoodies.uif_lite.component.Factory;
import com.jgoodies.uif_lite.panel.SimpleInternalFrame;
import com.rbnb.sapi.SAPIException;
/**
* Main frame for the application
*
* @author Jason P. Hanley
* @author Lawrence J. Miller
* @since 1.2
*/
public class ApplicationFrame extends JFrame implements MessageListener, ConnectionListener, StateListener {
static Log log = LogFactory.getLog(ApplicationFrame.class.getName());
private DataViewer dataViewer;
private RBNBController rbnb;
private DataPanelManager dataPanelManager;
private BusyDialog busyDialog;
private LoadingDialog loadingDialog;
private JFrame frame;
private GridBagConstraints c;
private JMenuBar menuBar;
private ChannelListPanel channelListPanel;
private MetadataPanel metadataPanel;
private JSplitPane leftPanel;
private JPanel rightPanel;
private ControlPanel controlPanel;
/////////////////////////////////////////////////////////////////////////////LJM
private SendMarkerRDVPanel markerSubmitPanel = null;
private JCheckBoxMenuItem showMarkerMenuItem = null;
private SimpleInternalFrame markerFrame;
/////////////////////////////////////////////////////////////////////////////LJM
private StatusPanel statusPanel;
private DataPanelContainer dataPanelContainer;
private JSplitPane splitPane;
private AboutDialog aboutDialog;
private RBNBConnectionDialog rbnbConnectionDialog;
private Action fileAction;
private Action connectAction;
private Action disconnectAction;
private Action loadAction;
private Action saveAction;
private Action importAction;
private Action exportAction;
private Action exitAction;
private Action controlAction;
private Action realTimeAction;
private Action playAction;
private Action pauseAction;
private Action beginningAction;
private Action endAction;
private Action updateChannelListAction;
private Action dropDataAction;
private Action viewAction;
private Action showChannelListAction;
private Action showMetadataPanelAction;
private Action showControlPanelAction;
/////////////////////////////////////////////////////////////////////////////LJM
private Action showMarkerPanelAction;
/////////////////////////////////////////////////////////////////////////////LJM
private Action showStatusPanelAction;
private Action dataPanelAction;
private Action dataPanelHorizontalLayoutAction;
private Action dataPanelVerticalLayoutAction;
private Action showHiddenChannelsAction;
private Action fullScreenAction;
private Action windowAction;
private Action closeAllDataPanelsAction;
private Action helpAction;
private Action aboutAction;
private JLabel throbber;
private Icon throbberStop;
private Icon throbberAnim;
private Action gotoTimeAction;
private JumpDateTimeDialog jumpDateTimeDialog;
public ApplicationFrame(DataViewer dataViewer, RBNBController rbnb, DataPanelManager dataPanelManager, boolean isApplet) {
super();
this.dataViewer = dataViewer;
this.rbnb = rbnb;
this.dataPanelManager = dataPanelManager;
busyDialog = null;
loadingDialog = null;
initFrame(isApplet);
/////////////////////////////////////////////////////////////////////////////LJM
// Initially, these should be off
markerFrame.setVisible (false);
controlPanel.markerPanel.setVisible (false);
controlPanel.markerLabel.setVisible (false);
/////////////////////////////////////////////////////////////////////////////LJM
}
private void initFrame(boolean isApplet) {
frame = this;
if (!isApplet) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dataViewer.exit();
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.setBounds(0, 0, 800, 600);
frame.setIconImage(DataViewer.getImage("icons/RDV.gif"));
frame.setTitle("RDV");
}
c = new GridBagConstraints();
initActions();
initMenuBar();
initChannelListPanel();
initMetadataPanel();
initLeftPanel();
initRightPanel();
initControls();
/////////////////////////////////////////////////////////////////////////////LJM
initSubmit ();
/////////////////////////////////////////////////////////////////////////////LJM
initDataPanelContainer();
initStatus();
initSplitPane();
channelListPanel.addChannelSelectionListener(metadataPanel);
rbnb.addSubscriptionListener(controlPanel);
rbnb.addTimeListener(controlPanel);
rbnb.addTimeListener(statusPanel);
rbnb.addStateListener(channelListPanel);
rbnb.addStateListener(statusPanel);
rbnb.addStateListener(controlPanel);
rbnb.addStateListener(this);
rbnb.getMetadataManager().addMetadataListener(channelListPanel);
rbnb.getMetadataManager().addMetadataListener(metadataPanel);
rbnb.getMetadataManager().addMetadataListener(controlPanel);
rbnb.addPlaybackRateListener(statusPanel);
rbnb.addTimeScaleListener(statusPanel);
rbnb.addMessageListener(this);
rbnb.addConnectionListener(this);
/////////////////////////////////////////////////////////////////////////////LJM
rbnb.addConnectionListener (markerSubmitPanel);
/////////////////////////////////////////////////////////////////////////////LJM
if (!isApplet) {
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
private void initActions() {
fileAction = new DataViewerAction("File", "File Menu", KeyEvent.VK_F);
connectAction = new DataViewerAction("Connect", "Connect to RBNB server", KeyEvent.VK_C, KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)) {
public void actionPerformed(ActionEvent ae) {
if (rbnbConnectionDialog == null) {
rbnbConnectionDialog = new RBNBConnectionDialog(frame, rbnb, dataPanelManager);
} else {
rbnbConnectionDialog.setVisible(true);
}
/////////////////////////////////////////////////////////////////////////////LJM
// Clear out and disable event markers for changing to a new turbine
controlPanel.markerPanel.clearData ();
/////////////////////////////////////////////////////////////////////////////LJM
}
};
disconnectAction = new DataViewerAction("Disconnect", "Disconnect from RBNB server", KeyEvent.VK_D, KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)) {
public void actionPerformed(ActionEvent ae) {
dataPanelManager.closeAllDataPanels();
/////////////////////////////////////////////////////////////////////////////LJM
try {
markerSubmitPanel.sendClosingMarker ();
markerSubmitPanel.closeTurbine ();
} catch (IOException ioe) {
log.error ("Sending closing marker: " + ioe);
} catch (TransformerException te) {
log.error ("Sending closing marker: " + te);
}
/////////////////////////////////////////////////////////////////////////////LJM
rbnb.disconnect();
/////////////////////////////////////////////////////////////////////////////LJM
controlPanel.markerPanel.clearData ();
markerFrame.setVisible (false);
/////////////////////////////////////////////////////////////////////////////LJM
}
};
loadAction = new DataViewerAction("Load Setup", "Load data viewer setup from file") {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new RDVFileFilter());
chooser.setApproveButtonText("Load");
chooser.setApproveButtonToolTipText("Load selected file");
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION) {
dataViewer.getConfigurationManager().loadConfiguration(chooser.getSelectedFile());
}
}
};
saveAction = new DataViewerAction("Save Setup", "Save data viewer setup to file") {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new RDVFileFilter());
int returnVal = chooser.showSaveDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (file.getName().indexOf(".") == -1) {
file = new File(file.getAbsolutePath() + ".rdv");
}
// prompt for overwrite if file already exists
if (file.exists()) {
int overwriteReturn = JOptionPane.showConfirmDialog(null,
file.getName() + " already exists. Do you want to overwrite it?",
"Overwrite file?",
JOptionPane.YES_NO_OPTION);
if (overwriteReturn == JOptionPane.NO_OPTION) {
return;
}
}
dataViewer.getConfigurationManager().saveConfiguration(file);
}
}
};
importAction = new DataViewerAction("Import Data", "Import local data to RBNB server", KeyEvent.VK_I, "icons/import.gif") {
public void actionPerformed(ActionEvent ae) {
showImportDialog();
}
};
exportAction = new DataViewerAction("Export Data", "Export data on server to local computer", KeyEvent.VK_E, "icons/export.gif") {
public void actionPerformed(ActionEvent ae) {
showExportDialog();
}
};
exitAction = new DataViewerAction("Exit", "Exit RDV", KeyEvent.VK_X, KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK)) {
public void actionPerformed(ActionEvent ae) {
dataViewer.exit();
}
};
controlAction = new DataViewerAction("Control", "Control Menu", KeyEvent.VK_C);
realTimeAction = new DataViewerAction("Real Time", "View data in real time", KeyEvent.VK_R, KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), "icons/rt.gif") {
public void actionPerformed(ActionEvent ae) {
//////////////////////////////////////////////////////////////////////////// LJM
// DOTOO refetch markers and repaint the panel
controlPanel.markerPanel.repaint ();
//////////////////////////////////////////////////////////////////////////// LJM
rbnb.monitor();
}
};
playAction = new DataViewerAction("Play", "Playback data", KeyEvent.VK_P, KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "icons/play.gif") {
public void actionPerformed(ActionEvent ae) {
rbnb.play();
}
};
pauseAction = new DataViewerAction("Pause", "Pause data display", KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_U, 0), "icons/play.gif") {
public void actionPerformed(ActionEvent ae) {
rbnb.pause();
}
};
beginningAction = new DataViewerAction("Go to beginning", "Move the location to the start of the data", KeyEvent.VK_B, KeyStroke.getKeyStroke(KeyEvent.VK_B, 0), "icons/begin.gif") {
public void actionPerformed(ActionEvent ae) {
controlPanel.setLocationBegin();
}
};
endAction = new DataViewerAction("Go to end", "Move the location to the end of the data", KeyEvent.VK_E, KeyStroke.getKeyStroke(KeyEvent.VK_E, 0), "icons/end.gif") {
public void actionPerformed(ActionEvent ae) {
controlPanel.setLocationEnd();
}
};
gotoTimeAction = new DataViewerAction("Go to Time", "Move the location to specific date time of the data", KeyEvent.VK_T, KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK), "icons/begin.gif") {
public void actionPerformed(ActionEvent ae) {
if (jumpDateTimeDialog == null) {
jumpDateTimeDialog = new JumpDateTimeDialog(frame, rbnb, dataPanelManager);
} else {
jumpDateTimeDialog.setVisible(true);
}
}
};
updateChannelListAction = new DataViewerAction("Update Channel List", "Update the channel list", KeyEvent.VK_U, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "icons/refresh.gif") {
public void actionPerformed(ActionEvent ae) {
rbnb.updateMetadata();
}
};
dropDataAction = new DataViewerAction("Drop Data", "Drop data if plaback can't keep up with data rate", KeyEvent.VK_D, "icons/drop_data.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
rbnb.dropData(menuItem.isSelected());
}
};
viewAction = new DataViewerAction("View", "View Menu", KeyEvent.VK_V);
showChannelListAction = new DataViewerAction("Show Channels", "", KeyEvent.VK_L, "icons/channels.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
channelListPanel.setVisible(menuItem.isSelected());
leftPanel.resetToPreferredSizes();
}
};
showMetadataPanelAction = new DataViewerAction("Show Properties", "", KeyEvent.VK_P, "icons/properties.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
metadataPanel.setVisible(menuItem.isSelected());
leftPanel.resetToPreferredSizes();
}
};
showControlPanelAction = new DataViewerAction("Show Control Panel", "", KeyEvent.VK_C, "icons/control.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
controlPanel.setVisible(menuItem.isSelected());
}
};
showMarkerPanelAction = new DataViewerAction ("Show Event Markers", "", KeyEvent.VK_M, "icons/channels.gif") {
public void actionPerformed (ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource ();
markerFrame.setVisible (
menuItem.isSelected () &&
markerSubmitPanel.isConnected ()
);
controlPanel.markerPanel.setVisible (menuItem.isSelected ());
controlPanel.markerLabel.setVisible (menuItem.isSelected ());
controlPanel.markerPanel.repaint ();
}
};
showStatusPanelAction = new DataViewerAction("Show Status Panel", "", KeyEvent.VK_S, "icons/info.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
statusPanel.setVisible(menuItem.isSelected());
}
};
// changed the name of this to "arrange" - more for case 4719
dataPanelAction = new DataViewerAction("Arrange", "Arrange Data Panel Orientation", KeyEvent.VK_D);
/* Display the data panels horizontally.
* LJM exchanged HORIZONTAL and VERTICAL to invert semantics to apply to the
* windows theselves, rather than their arrangement for case 4719 */
dataPanelHorizontalLayoutAction = new DataViewerAction("Horizontal Data Panel Orientation", "", -1, "icons/vertical.gif") {
public void actionPerformed(ActionEvent ae) {
dataPanelContainer.setLayout(DataPanelContainer.VERTICAL_LAYOUT);
}
};
dataPanelVerticalLayoutAction = new DataViewerAction("Vertical Data Panel Orientation", "", -1, "icons/horizontal.gif") {
public void actionPerformed(ActionEvent ae) {
dataPanelContainer.setLayout(DataPanelContainer.HORIZONTAL_LAYOUT);
}
};
showHiddenChannelsAction = new DataViewerAction("Show Hidden Channels", "", KeyEvent.VK_H, "icons/hidden.gif") {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
boolean selected = menuItem.isSelected();
channelListPanel.showHiddenChannels(selected);
}
};
fullScreenAction = new DataViewerAction("Full Screen", "", KeyEvent.VK_F, KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0)) {
public void actionPerformed(ActionEvent ae) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ae.getSource();
if (menuItem.isSelected()) {
if (enterFullScreenMode()) {
menuItem.setSelected(true);
} else {
menuItem.setSelected(false);
}
} else {
leaveFullScreenMode();
menuItem.setSelected(false);
}
}
};
windowAction = new DataViewerAction("Window", "Window Menu", KeyEvent.VK_W);
closeAllDataPanelsAction = new DataViewerAction("Close all data panels", "", KeyEvent.VK_C, "icons/closeall.gif") {
public void actionPerformed(ActionEvent ae) {
dataPanelManager.closeAllDataPanels();
}
};
helpAction = new DataViewerAction("Help", "Help Menu", KeyEvent.VK_H);
aboutAction = new DataViewerAction("About RDV", "", KeyEvent.VK_A) {
public void actionPerformed(ActionEvent ae) {
if (aboutDialog == null) {
aboutDialog = new AboutDialog(frame);
} else {
aboutDialog.setVisible(true);
}
}
};
}
private void initMenuBar() {
menuBar = new JMenuBar();
menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE);
JMenuItem menuItem;
JMenu fileMenu = new JMenu(fileAction);
menuItem = new JMenuItem(connectAction);
fileMenu.add(menuItem);
menuItem = new JMenuItem(disconnectAction);
fileMenu.add(menuItem);
fileMenu.addSeparator();
menuItem = new JMenuItem(loadAction);
fileMenu.add(menuItem);
menuItem = new JMenuItem(saveAction);
fileMenu.add(menuItem);
fileMenu.addSeparator();
menuItem = new JMenuItem(importAction);
// LJM 060413 - this function disabled for the 1.3 release
// fileMenu.add(menuItem);
menuItem = new JMenuItem(exportAction);
// LJM 060424 - this function disabled for the 1.3 release
// fileMenu.add(menuItem);
//fileMenu.addSeparator();
menuItem = new JMenuItem(exitAction);
fileMenu.add(menuItem);
menuBar.add(fileMenu);
JMenu controlMenu = new JMenu(controlAction);
menuItem = new JMenuItem(realTimeAction);
controlMenu.add(menuItem);
menuItem = new JMenuItem(playAction);
controlMenu.add(menuItem);
menuItem = new JMenuItem(pauseAction);
controlMenu.add(menuItem);
controlMenu.addSeparator();
menuItem = new JMenuItem(beginningAction);
controlMenu.add(menuItem);
menuItem = new JMenuItem(endAction);
controlMenu.add(menuItem);
menuItem = new JMenuItem(gotoTimeAction);
controlMenu.add(menuItem);
menuBar.add(controlMenu);
controlMenu.addSeparator();
menuItem = new JMenuItem(updateChannelListAction);
controlMenu.add(menuItem);
controlMenu.addSeparator();
menuItem = new JCheckBoxMenuItem(dropDataAction);
menuItem.setSelected(true);
controlMenu.add(menuItem);
JMenu viewMenu = new JMenu(viewAction);
menuItem = new JCheckBoxMenuItem(showChannelListAction);
menuItem.setSelected(true);
viewMenu.add(menuItem);
menuItem = new JCheckBoxMenuItem(showMetadataPanelAction);
menuItem.setSelected(true);
viewMenu.add(menuItem);
menuItem = new JCheckBoxMenuItem(showControlPanelAction);
menuItem.setSelected(true);
viewMenu.add(menuItem);
showMarkerMenuItem = new JCheckBoxMenuItem (showMarkerPanelAction);
showMarkerMenuItem.setSelected (false);
viewMenu.add (showMarkerMenuItem);
menuItem = new JCheckBoxMenuItem(showStatusPanelAction);
menuItem.setSelected(true);
viewMenu.add(menuItem);
viewMenu.addSeparator();
menuItem = new JCheckBoxMenuItem(showHiddenChannelsAction);
menuItem.setSelected(false);
viewMenu.add(menuItem);
viewMenu.addSeparator();
menuItem = new JCheckBoxMenuItem(fullScreenAction);
menuItem.setSelected(false);
viewMenu.add(menuItem);
menuBar.add(viewMenu);
JMenu windowMenu = new JMenu(windowAction);
ArrayList extensions = dataPanelManager.getExtensions();
for (int i=0; i<extensions.size(); i++) {
final Extension extension = (Extension)extensions.get(i);
Action action = new DataViewerAction("Add " + extension.getName(), "", KeyEvent.VK_J) {
public void actionPerformed(ActionEvent ae) {
try {
dataPanelManager.createDataPanel(extension);
} catch (Exception e) {
log.error("Unable to open data panel provided by extension " + extension.getName() + " (" + extension.getID() + ").");
e.printStackTrace();
}
}
};
menuItem = new JMenuItem(action);
windowMenu.add(menuItem);
}
windowMenu.addSeparator();
menuItem = new JMenuItem(closeAllDataPanelsAction);
windowMenu.add(menuItem);
windowMenu.addSeparator();
JMenu dataPanelSubMenu = new JMenu(dataPanelAction);
ButtonGroup dataPanelLayoutGroup = new ButtonGroup();
menuItem = new JRadioButtonMenuItem(dataPanelHorizontalLayoutAction);
dataPanelSubMenu.add(menuItem);
dataPanelLayoutGroup.add(menuItem);
menuItem = new JRadioButtonMenuItem(dataPanelVerticalLayoutAction);
menuItem.setSelected(true);
dataPanelSubMenu.add(menuItem);
dataPanelLayoutGroup.add(menuItem);
windowMenu.add(dataPanelSubMenu);
menuBar.add(windowMenu);
JMenu helpMenu = new JMenu(helpAction);
menuItem = new JMenuItem(aboutAction);
helpMenu.add(menuItem);
menuBar.add(helpMenu);
menuBar.add(Box.createHorizontalGlue());
throbberStop = DataViewer.getIcon("icons/throbber.png");
throbberAnim = DataViewer.getIcon("icons/throbber_anim.gif");
throbber = new JLabel(throbberStop);
throbber.setBorder(new EmptyBorder(0,0,0,4));
menuBar.add(throbber, BorderLayout.EAST);
frame.setJMenuBar(menuBar);
}
private void initChannelListPanel() {
channelListPanel = new ChannelListPanel(dataPanelManager, rbnb, this);
channelListPanel.setMinimumSize(new Dimension(0, 0));
log.info("Created channel list panel.");
}
private void initMetadataPanel() {
metadataPanel = new MetadataPanel(rbnb);
log.info("Created metadata panel");
}
private void initLeftPanel() {
leftPanel = Factory.createStrippedSplitPane(
JSplitPane.VERTICAL_SPLIT,
channelListPanel,
metadataPanel,
0.65f);
leftPanel.setContinuousLayout(true);
leftPanel.setBorder(new EmptyBorder(8, 8, 8, 0));
log.info("Created left panel");
}
private void initRightPanel() {
rightPanel = new JPanel();
rightPanel.setMinimumSize(new Dimension(0, 0));
rightPanel.setLayout(new GridBagLayout());
}
private void initControls() {
controlPanel = new ControlPanel(rbnb);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.ipadx = 0;
c.ipady = 0;
c.insets = new java.awt.Insets(8,0,0,8);
c.anchor = GridBagConstraints.NORTHWEST;
rightPanel.add(controlPanel, c);
log.info("Added control panel.");
}
private void initDataPanelContainer() {
dataPanelContainer = dataPanelManager.getDataPanelContainer();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.ipadx = 0;
c.ipady = 0;
c.insets = new java.awt.Insets(8,0,8,8);
c.anchor = GridBagConstraints.NORTHWEST;
rightPanel.add(dataPanelContainer, c);
log.info("Added data panel container.");
}
/////////////////////////////////////////////////////////////////////////////LJM
// Marker submission GUI panel
private void initSubmit () {
markerSubmitPanel = new SendMarkerRDVPanel (null, rbnb, this.controlPanel.markerPanel, this);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.weighty = 0;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.gridheight = 1;
c.ipadx = 0;
c.ipady = 0;
c.insets = new java.awt.Insets (0, 0, 5, 8);
c.anchor = GridBagConstraints.SOUTHWEST;
markerFrame = new SimpleInternalFrame (
DataViewer.getIcon("icons/info.gif"),
"Event Marker Submission",
null,
markerSubmitPanel
);
rightPanel.add (markerFrame, c);
log.info ("Added Marker Submission Panel.");
} // initSubmit ()
/////////////////////////////////////////////////////////////////////////////LJM
private void initStatus() {
statusPanel = new StatusPanel();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.ipadx = 0;
c.ipady = 0;
c.insets = new java.awt.Insets(0,0,8,8);
c.anchor = GridBagConstraints.NORTHWEST;
rightPanel.add(statusPanel, c);
log.info("Added status panel.");
}
private void initSplitPane() {
splitPane = Factory.createStrippedSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftPanel,
rightPanel,
0.2f);
splitPane.setContinuousLayout(true);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
}
public ControlPanel getControlPanel() {
return controlPanel;
}
private boolean enterFullScreenMode() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = ge.getScreenDevices();
for (int i=0; i<devices.length; i++) {
GraphicsDevice device = devices[i];
if (device.isFullScreenSupported() && device.getFullScreenWindow() == null) {
log.info("Switching to full screen mode.");
setVisible(false);
try {
device.setFullScreenWindow(this);
} catch (InternalError e) {
log.error("Failed to switch to full screen exclusive mode.");
e.printStackTrace();
setVisible(true);
return false;
}
dispose();
setUndecorated(true);
setVisible(true);
requestFocus();
return true;
}
}
log.warn("No screens available or full screen exclusive mode is unsupported on your platform.");
postError("Full screen mode is not supported on your platform.");
return false;
}
private void leaveFullScreenMode() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = ge.getScreenDevices();
for (int i=0; i<devices.length; i++) {
GraphicsDevice device = devices[i];
if (device.isFullScreenSupported() && device.getFullScreenWindow() == this) {
log.info("Leaving full screen mode.");
setVisible(false);
device.setFullScreenWindow(null);
dispose();
setUndecorated(false);
setVisible(true);
break;
}
}
}
public void postError(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
}
public void postStatus(String statusMessage) {
JOptionPane.showMessageDialog(this, statusMessage, "Error", JOptionPane.INFORMATION_MESSAGE);
}
public void showImportDialog() {
showImportDialog(null);
}
public void showImportDialog(String sourceName) {
new ImportDialog(frame, rbnb, sourceName);
}
public void showExportDialog() {
List channels = channelListPanel.getSelectedChannels();
if (channels.size() == 0) {
channels = RBNBUtilities.getAllChannels(rbnb.getMetadataManager().getMetadataChannelTree(), channelListPanel.isShowingHiddenChannles());
}
showExportDialog(channels);
}
public void showExportDialog(List channels) {
new ExportDialog(frame, rbnb, channels);
}
class DataViewerAction extends AbstractAction {
boolean selected = false;
public DataViewerAction(String text) {
this(text, null, -1, null, null);
}
public DataViewerAction(String text, String desc) {
this(text, desc, -1, null, null);
}
public DataViewerAction(String text, int mnemonic) {
this(text, null, mnemonic, null, null);
}
public DataViewerAction(String text, String desc, int mnemonic) {
this(text, desc, mnemonic, null, null);
}
public DataViewerAction(String text, String desc, int mnemonic, String iconFileName) {
this(text, desc, mnemonic, null, iconFileName);
}
public DataViewerAction(String text, String desc, int mnemonic, KeyStroke accelerator) {
this(text, desc, mnemonic, accelerator, null);
}
public DataViewerAction(String text, String desc, int mnemonic, KeyStroke accelerator, String iconFileName) {
super(text);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, new Integer(mnemonic));
putValue(ACCELERATOR_KEY, accelerator);
putValue(SMALL_ICON, DataViewer.getIcon(iconFileName));
}
public void actionPerformed(ActionEvent ae) {}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void connecting() {
busyDialog = new BusyDialog(this);
busyDialog.setCancelActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rbnb.cancelConnect();
}
});
busyDialog.start();
startThrobber();
/////////////////////////////////////////////////////////////////////////////LJM
/* Going to a new turbine, so flush out the data from the old one. */
controlPanel.markerPanel.clearData ();
/////////////////////////////////////////////////////////////////////////////LJM
}
public void connected() {
busyDialog.close();
busyDialog = null;
stopThrobber();
/////////////////////////////////////////////////////////////////////////////LJM
/* Going to a new turbine, so flush out the data from the old one. */
markerFrame.setVisible (
showMarkerMenuItem.isSelected ()
/*&& markerSubmitPanel.isConnected ()*/
);
controlPanel.markerPanel.clearData ();
// TODO
// reset the scanning of past event markers when we first connect
controlPanel.markerPanel.doScanPastMarkers = true;
////////////////////////////////////////////////////////////////////////////LJM
}
public void connectionFailed() {
busyDialog.close();
busyDialog = null;
stopThrobber();
}
public void postState(int newState, int oldState) {
if (newState == Player.STATE_DISCONNECTED) {
controlAction.setEnabled(false);
disconnectAction.setEnabled(false);
importAction.setEnabled(false);
exportAction.setEnabled(false);
} else if (newState != Player.STATE_EXITING) {
controlAction.setEnabled(true);
disconnectAction.setEnabled(true);
importAction.setEnabled(true);
exportAction.setEnabled(true);
}
if (newState == Player.STATE_LOADING || newState == Player.STATE_PLAYING || newState == Player.STATE_MONITORING) {
startThrobber();
} else {
stopThrobber();
}
if (newState == Player.STATE_LOADING) {
loadingDialog = new LoadingDialog(this);
loadingDialog.start();
} else {
if (loadingDialog != null) {
loadingDialog.close();
loadingDialog = null;
}
}
}
private void startThrobber() {
throbber.setIcon(throbberAnim);
}
private void stopThrobber() {
throbber.setIcon(throbberStop);
}
public class RDVFileFilter extends FileFilter {
public boolean accept(File f) {
return !f.isFile() || f.getName().endsWith(".rdv");
}
public String getDescription() {
return "RDV Configuration Files (*.rdv)";
}
};
} |
package org.ojalgo.optimisation.convex;
import static org.ojalgo.constant.PrimitiveMath.*;
import org.ojalgo.function.PrimitiveFunction;
import org.ojalgo.matrix.store.MatrixStore;
import org.ojalgo.matrix.store.PhysicalStore;
import org.ojalgo.matrix.store.PrimitiveDenseStore;
import org.ojalgo.optimisation.Optimisation;
/**
* Solves optimisation problems of the form:
* <p>
* min 1/2 [X]<sup>T</sup>[Q][X] - [C]<sup>T</sup>[X]<br>
* when [AE][X] == [BE]
* </p>
*
* @author apete
*/
final class QPESolver extends ConstrainedSolver {
private boolean myFeasible = false;
private final PrimitiveDenseStore myIterationX;
QPESolver(final ConvexSolver.Builder matrices, final Optimisation.Options solverOptions) {
super(matrices, solverOptions);
myIterationX = PrimitiveDenseStore.FACTORY.makeZero(this.countVariables(), 1L);
}
private boolean isFeasible() {
boolean retVal = true;
final MatrixStore<Double> tmpSE = this.getSE();
for (int i = 0; retVal && (i < tmpSE.countRows()); i++) {
if (!options.slack.isZero(tmpSE.doubleValue(i))) {
retVal = false;
}
}
return retVal;
}
@Override
protected boolean initialise(final Result kickStarter) {
super.initialise(kickStarter);
if ((kickStarter != null) && kickStarter.getState().isFeasible()) {
this.getSolutionX().fillMatching(kickStarter);
if (!(myFeasible = this.isFeasible())) {
this.getSolutionX().fillAll(ZERO);
}
} else {
this.getSolutionX().fillAll(ZERO);
myFeasible = false; // Could still be feasible, but doesn't matter...
}
return true;
}
@Override
protected boolean needsAnotherIteration() {
return this.countIterations() < 1;
}
@Override
protected void performIteration() {
this.getIterationQ();
final MatrixStore<Double> tmpIterC = this.getIterationC();
final MatrixStore<Double> tmpIterA = this.getIterationA();
final MatrixStore<Double> tmpIterB = this.getIterationB();
boolean tmpSolvable = false;
final PrimitiveDenseStore tmpIterX = myIterationX;
final PrimitiveDenseStore tmpIterL = PrimitiveDenseStore.FACTORY.makeZero(tmpIterA.countRows(), 1L);
if ((tmpIterA.countRows() < tmpIterA.countColumns()) && (tmpSolvable = this.isSolvableQ())) {
// Q is SPD
// Actual/normal optimisation problem
final MatrixStore<Double> tmpInvQAT = this.getSolutionQ(tmpIterA.transpose());
// TODO Only 1 column change inbetween active set iterations (add or remove 1 column)
// Negated Schur complement
final MatrixStore<Double> tmpS = tmpIterA.multiply(tmpInvQAT);
// TODO Symmetric, only need to calculate halv the Schur complement
if (tmpSolvable = this.computeGeneral(tmpS)) {
// tmpX temporarely used to store tmpInvQC
final MatrixStore<Double> tmpInvQC = this.getSolutionQ(tmpIterC, tmpIterX); //TODO Constant if C doesn't change
this.getSolutionGeneral(tmpIterA.multiply(tmpInvQC).subtract(tmpIterB), tmpIterL);
this.getSolutionQ(tmpIterC.subtract(tmpIterA.transpose().multiply(tmpIterL)), tmpIterX);
}
}
if (!tmpSolvable) {
// The above failed, try solving the full KKT system instaed
final PrimitiveDenseStore tmpXL = PrimitiveDenseStore.FACTORY.makeZero(this.countVariables() + this.countIterationConstraints(), 1L);
tmpSolvable = this.solveFullKKT(tmpXL);
tmpIterX.fillMatching(tmpXL.logical().limits(this.countVariables(), 1).get());
tmpIterL.fillMatching(tmpXL.logical().offsets(this.countVariables(), 0).get());
}
if (!tmpSolvable && this.isDebug()) {
options.debug_appender.println("KKT system unsolvable!");
options.debug_appender.printmtrx("KKT", this.getIterationKKT().collect(PrimitiveDenseStore.FACTORY));
options.debug_appender.printmtrx("RHS", this.getIterationRHS().collect(PrimitiveDenseStore.FACTORY));
}
if (tmpSolvable) {
this.setState(State.OPTIMAL);
if (myFeasible) {
this.getSolutionX().modifyMatching(PrimitiveFunction.ADD, tmpIterX);
} else {
this.getSolutionX().fillMatching(tmpIterX);
}
// this.getLE().fillMatching(tmpIterL);
} else {
if (myFeasible) {
this.setState(State.FEASIBLE);
} else {
this.setState(State.INFEASIBLE);
this.getSolutionX().fillAll(ZERO);
}
}
}
@Override
int countIterationConstraints() {
return (int) this.getIterationA().countRows();
}
@Override
final MatrixStore<Double> getIterationA() {
return this.getMatrixAE();
}
@Override
final MatrixStore<Double> getIterationB() {
if (myFeasible) {
return MatrixStore.PRIMITIVE.makeZero(this.countEqualityConstraints(), 1).get();
} else {
return this.getMatrixBE();
}
}
@Override
final MatrixStore<Double> getIterationC() {
if (myFeasible) {
final MatrixStore<Double> mtrxQ = this.getMatrixQ();
final MatrixStore<Double> mtrxC = this.getMatrixC();
final PhysicalStore<Double> solX = this.getSolutionX();
return mtrxC.subtract(mtrxQ.multiply(solX));
} else {
return this.getMatrixC();
}
}
} |
package org.olap4j.driver.xmla;
import org.olap4j.OlapDatabaseMetaData;
import org.olap4j.OlapException;
import org.olap4j.impl.Named;
import org.olap4j.impl.Olap4jUtil;
import org.olap4j.metadata.*;
/**
* Implementation of {@link org.olap4j.metadata.Catalog}
* for XML/A providers.
*
* @author jhyde
* @version $Id$
* @since May 23, 2007
*/
class XmlaOlap4jCatalog implements Catalog, Named {
final XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData;
private final String name;
final DeferredNamedListImpl<XmlaOlap4jSchema> schemas;
private final XmlaOlap4jDatabase database;
XmlaOlap4jCatalog(
XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData,
XmlaOlap4jDatabase database,
String name)
{
this.database = database;
assert olap4jDatabaseMetaData != null;
assert name != null;
this.olap4jDatabaseMetaData = olap4jDatabaseMetaData;
this.name = name;
// Some servers don't support MDSCHEMA_MDSCHEMATA, so we will
// override the list class so it tries it first, and falls
// back to the MDSCHEMA_CUBES trick, where ask for the cubes,
// restricting results on the catalog, and while
// iterating on the cubes, take the schema name from this recordset.
// Many servers (SSAS for example) won't support the schema name column
// in the returned rowset. This has to be taken into account as well.
this.schemas =
new DeferredNamedListImpl<XmlaOlap4jSchema>(
XmlaOlap4jConnection.MetadataRequest.DBSCHEMA_SCHEMATA,
new XmlaOlap4jConnection.Context(
olap4jDatabaseMetaData.olap4jConnection,
olap4jDatabaseMetaData,
this,
null, null, null, null, null),
new XmlaOlap4jConnection.CatalogSchemaHandler(this.name),
null)
{
@Override
protected void populateList(NamedList<XmlaOlap4jSchema> list)
throws OlapException
{
// First try DBSCHEMA_SCHEMATA
try {
super.populateList(list);
} catch (OlapException e) {
// Fallback to MDSCHEMA_CUBES trick
XmlaOlap4jConnection conn =
XmlaOlap4jCatalog.this
.olap4jDatabaseMetaData.olap4jConnection;
conn.populateList(
list,
new XmlaOlap4jConnection.Context(
conn,
conn.olap4jDatabaseMetaData,
XmlaOlap4jCatalog.this,
null, null, null, null, null),
XmlaOlap4jConnection.MetadataRequest
.MDSCHEMA_CUBES,
new XmlaOlap4jConnection.CatalogSchemaHandler(
XmlaOlap4jCatalog.this.name),
new Object[0]);
}
}
};
}
public int hashCode() {
return name.hashCode();
}
public boolean equals(Object obj) {
if (obj instanceof XmlaOlap4jCatalog) {
XmlaOlap4jCatalog that = (XmlaOlap4jCatalog) obj;
return this.name.equals(that.name);
}
return false;
}
public NamedList<Schema> getSchemas() throws OlapException {
return Olap4jUtil.cast(schemas);
}
public String getName() {
return name;
}
public OlapDatabaseMetaData getMetaData() {
return olap4jDatabaseMetaData;
}
public XmlaOlap4jDatabase getDatabase() {
return database;
}
}
// End XmlaOlap4jCatalog.java |
package org.subethamail.smtp.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
import javax.annotation.concurrent.GuardedBy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* ServerThread accepts TCP connections to the server socket and starts a new
* {@link Session} thread for each connection which will handle the connection.
* On shutdown it terminates not only this thread, but the session threads too.
*/
class ServerThread extends Thread
{
private final Logger log = LoggerFactory.getLogger(ServerThread.class);
private final SMTPServer server;
private final ServerSocket serverSocket;
/**
* A semaphore which is used to prevent accepting new connections by
* blocking this thread if the allowed count of open connections is already
* reached.
*/
private final Semaphore connectionPermits;
/**
* The list of currently running sessions.
*/
@GuardedBy("this")
private final Set<Session> sessionThreads;
/**
* A flag which indicates that this SMTP port and all of its open
* connections are being shut down.
*/
private volatile boolean shuttingDown;
public ServerThread(SMTPServer server, ServerSocket serverSocket)
{
super(ServerThread.class.getName() + " " + server.getDisplayableLocalSocketAddress());
this.server = server;
this.serverSocket = serverSocket;
// reserve a few places for graceful disconnects with informative
// messages
int countOfConnectionPermits = server.getMaxConnections() + 10;
this.connectionPermits = new Semaphore(countOfConnectionPermits);
this.sessionThreads = new HashSet<Session>(countOfConnectionPermits * 4 / 3 + 1);
}
/**
* This method is called by this thread when it starts up. To safely cause
* this to exit, call {@link #shutdown()}.
*/
@Override
public void run()
{
MDC.put("smtpServerLocalSocketAddress", server.getDisplayableLocalSocketAddress());
log.info("SMTP server {} started", server.getDisplayableLocalSocketAddress());
try
{
runAcceptLoop();
log.info("SMTP server {} stopped", server.getDisplayableLocalSocketAddress());
}
catch (RuntimeException e)
{
log.error("Unexpected exception in server socket thread, server is stopped", e);
throw e;
}
catch (Error e)
{
log.error("Unexpected error in server socket thread, server is stopped", e);
throw e;
}
finally
{
MDC.remove("smtpServerLocalSocketAddress");
}
}
/**
* Accept connections and run them in session threads until shutdown.
*/
private void runAcceptLoop()
{
while (!this.shuttingDown)
{
try
{
// block if too many connections are open
connectionPermits.acquire();
}
catch (InterruptedException consumed)
{
continue; // exit or retry
}
Socket socket = null;
try
{
socket = this.serverSocket.accept();
}
catch (IOException e)
{
connectionPermits.release();
// it also happens during shutdown, when the socket is closed
if (!this.shuttingDown)
{
log.error("Error accepting connection", e);
// prevent a possible loop causing 100% processor usage
try
{
Thread.sleep(1000);
}
catch (InterruptedException consumed)
{
// fall through
}
}
continue;
}
Session sessionThread;
try
{
sessionThread = new Session(server, this, socket);
}
catch (IOException e)
{
connectionPermits.release();
log.error("Error while starting a connection", e);
try
{
socket.close();
}
catch (IOException e1)
{
log.debug("Cannot close socket after exception", e1);
}
continue;
}
// add thread before starting it,
// because it will check the count of sessions
synchronized (this)
{
this.sessionThreads.add(sessionThread);
}
sessionThread.start();
}
}
/**
* Closes the server socket and all client sockets.
*/
public void shutdown()
{
// First make sure we aren't accepting any new connections
shutdownServerThread();
// Shut down any open connections.
shutdownSessions();
}
private void shutdownServerThread()
{
shuttingDown = true;
closeServerSocket();
interrupt();
}
/**
* Closes the serverSocket in an orderly way.
*/
private void closeServerSocket()
{
try
{
this.serverSocket.close();
log.debug("SMTP Server socket shut down");
}
catch (IOException e)
{
log.error("Failed to close server socket.", e);
}
}
private synchronized void shutdownSessions()
{
for (Session sessionThread : sessionThreads)
{
sessionThread.quit();
}
}
public synchronized boolean hasTooManyConnections()
{
return sessionThreads.size() > server.getMaxConnections();
}
public synchronized int getNumberOfConnections()
{
return sessionThreads.size();
}
/**
* Registers that the specified {@link Session} thread ended. Session
* threads must call this function.
*/
public void sessionEnded(Session session)
{
synchronized (this)
{
sessionThreads.remove(session);
}
connectionPermits.release();
}
} |
/*
* $Id$
* $URL$
*/
package org.subethamail.web.action;
import lombok.Getter;
import lombok.Setter;
import org.subethamail.web.Backend;
import org.subethamail.web.action.auth.AuthAction;
/**
* Deletes a message from a mailing list
*
* @author Jeff Schnitzer
*/
public class DeleteMessage extends AuthAction
{
@Getter @Setter Long listId;
@Getter @Setter Long msgId;
public void execute() throws Exception
{
this.listId = Backend.instance().getArchiver().deleteMail(this.msgId);
}
} |
package aQute.bnd.build;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.Processor;
import aQute.bnd.service.Strategy;
import aQute.lib.io.IO;
import aQute.libg.command.Command;
import aQute.libg.generics.Create;
/**
* A Project Launcher is a base class to be extended by launchers. Launchers are
* JARs that launch a framework and install a number of bundles and then run the
* framework. A launcher jar must specify a Launcher-Class manifest header. This
* class is instantiated and cast to a LauncherPlugin. This plug in is then
* asked to provide a ProjectLauncher. This project launcher is then used by the
* project to run the code. Launchers must extend this class.
*/
public abstract class ProjectLauncher extends Processor {
private final static Logger logger = LoggerFactory.getLogger(ProjectLauncher.class);
private final Project project;
private long timeout = 0;
private final List<String> classpath = new ArrayList<>();
private List<String> runbundles = Create.list();
private final List<String> runvm = new ArrayList<>();
private final List<String> runprogramargs = new ArrayList<>();
private Map<String, String> runproperties;
private Command java;
private Parameters runsystempackages;
private Parameters runsystemcapabilities;
private final List<String> activators = Create.list();
private File storageDir;
private boolean trace;
private boolean keep;
private int framework;
private File cwd;
private Collection<String> agents = new ArrayList<>();
private Set<NotificationListener> listeners = Collections.newSetFromMap(new IdentityHashMap<>());
protected Appendable out = System.out;
protected Appendable err = System.err;
protected InputStream in = System.in;
public final static int SERVICES = 10111;
public final static int NONE = 20123;
// MUST BE ALIGNED WITH LAUNCHER
public final static int OK = 0;
public final static int WARNING = -1;
public final static int ERROR = -2;
public final static int TIMEDOUT = -3;
public final static int UPDATE_NEEDED = -4;
public final static int CANCELED = -5;
public final static int DUPLICATE_BUNDLE = -6;
public final static int RESOLVE_ERROR = -7;
public final static int ACTIVATOR_ERROR = -8;
public final static int CUSTOM_LAUNCHER = -128;
public final static String EMBEDDED_ACTIVATOR = "Embedded-Activator";
public ProjectLauncher(Project project) throws Exception {
this.project = project;
updateFromProject();
}
/**
* Collect all the aspect from the project and set the local fields from
* them. Should be called
*
* @throws Exception
*/
protected void updateFromProject() throws Exception {
setCwd(project.getBase());
// pkr: could not use this because this is killing the runtests.
// project.refresh();
runbundles.clear();
Collection<Container> run = project.getRunbundles();
for (Container container : run) {
File file = container.getFile();
if (file != null && (file.isFile() || file.isDirectory())) {
runbundles.add(IO.absolutePath(file));
} else {
project.error("Bundle file \"%s\" does not exist, given error is %s", file, container.getError());
}
}
if (project.getRunBuilds()) {
File[] builds = project.getBuildFiles(true);
if (builds != null)
for (File file : builds)
runbundles.add(IO.absolutePath(file));
}
Collection<Container> runpath = project.getRunpath();
runsystempackages = new Parameters(project.mergeProperties(Constants.RUNSYSTEMPACKAGES), project);
runsystemcapabilities = new Parameters(project.mergeProperties(Constants.RUNSYSTEMCAPABILITIES), project);
framework = getRunframework(project.getProperty(Constants.RUNFRAMEWORK));
timeout = Processor.getDuration(project.getProperty(Constants.RUNTIMEOUT), 0);
trace = Processor.isTrue(project.getProperty(Constants.RUNTRACE));
runpath.addAll(project.getRunFw());
for (Container c : runpath) {
addClasspath(c);
}
runvm.addAll(project.getRunVM());
runprogramargs.addAll(project.getRunProgramArgs());
runproperties = project.getRunProperties();
storageDir = project.getRunStorage();
setKeep(project.getRunKeep());
}
private int getRunframework(String property) {
if (Constants.RUNFRAMEWORK_NONE.equalsIgnoreCase(property))
return NONE;
else if (Constants.RUNFRAMEWORK_SERVICES.equalsIgnoreCase(property))
return SERVICES;
return SERVICES;
}
public void addClasspath(Container container) throws Exception {
if (container.getError() != null) {
project.error("Cannot launch because %s has reported %s", container.getProject(), container.getError());
} else {
Collection<Container> members = container.getMembers();
for (Container m : members) {
String path = IO.absolutePath(m.getFile());
if (!classpath.contains(path)) {
Manifest manifest = m.getManifest();
if (manifest != null) {
// We are looking for any agents, used if
// -javaagent=true is set
String agentClassName = manifest.getMainAttributes()
.getValue("Premain-Class");
if (agentClassName != null) {
String agent = path;
if (container.getAttributes()
.get("agent") != null) {
agent += "=" + container.getAttributes()
.get("agent");
}
agents.add(agent);
}
Parameters exports = project.parseHeader(manifest.getMainAttributes()
.getValue(Constants.EXPORT_PACKAGE));
for (Entry<String, Attrs> e : exports.entrySet()) {
if (!runsystempackages.containsKey(e.getKey()))
runsystempackages.put(e.getKey(), e.getValue());
}
// Allow activators on the runpath. They are called
// after
// the framework is completely initialized wit the
// system
// context.
String activator = manifest.getMainAttributes()
.getValue(EMBEDDED_ACTIVATOR);
if (activator != null)
activators.add(activator);
}
classpath.add(path);
}
}
}
}
protected void addClasspath(Collection<Container> path) throws Exception {
for (Container c : Container.flatten(path)) {
addClasspath(c);
}
}
public void addRunBundle(String f) {
runbundles.add(f);
}
public Collection<String> getRunBundles() {
return runbundles;
}
public void addRunVM(String arg) {
runvm.add(arg);
}
public void addRunProgramArgs(String arg) {
runprogramargs.add(arg);
}
public List<String> getRunpath() {
return classpath;
}
public Collection<String> getClasspath() {
return classpath;
}
public Collection<String> getRunVM() {
return runvm;
}
@Deprecated
public Collection<String> getArguments() {
return getRunProgramArgs();
}
public Collection<String> getRunProgramArgs() {
return runprogramargs;
}
public Map<String, String> getRunProperties() {
return runproperties;
}
public File getStorageDir() {
return storageDir;
}
public abstract String getMainTypeName();
public abstract void update() throws Exception;
public int launch() throws Exception {
prepare();
java = new Command();
// Handle the environment
Map<String, String> env = getRunEnv();
for (Map.Entry<String, String> e : env.entrySet()) {
java.var(e.getKey(), e.getValue());
}
java.add(project.getProperty("java", getJavaExecutable()));
String javaagent = project.getProperty(Constants.JAVAAGENT);
if (Processor.isTrue(javaagent)) {
for (String agent : agents) {
java.add("-javaagent:" + agent);
}
}
String jdb = getRunJdb();
if (jdb != null) {
int port = 1044;
try {
port = Integer.parseInt(jdb);
} catch (Exception e) {
// ok, value can also be ok, or on, or true
}
String suspend = port > 0 ? "y" : "n";
java.add("-Xrunjdwp:server=y,transport=dt_socket,address=" + Math.abs(port) + ",suspend=" + suspend);
}
java.addAll(split(System.getenv("JAVA_OPTS"), "\\s+"));
java.add("-cp");
java.add(Processor.join(getClasspath(), File.pathSeparator));
java.addAll(getRunVM());
java.add(getMainTypeName());
java.addAll(getRunProgramArgs());
if (timeout != 0)
java.setTimeout(timeout + 1000, TimeUnit.MILLISECONDS);
File cwd = getCwd();
if (cwd != null)
java.setCwd(cwd);
logger.debug("cmd line {}", java);
try {
int result = java.execute(in, out, err);
if (result == Integer.MIN_VALUE)
return TIMEDOUT;
reportResult(result);
return result;
} finally {
cleanup();
listeners.clear();
}
}
private String getJavaExecutable() {
String javaHome = System.getProperty("java.home");
if (javaHome == null) {
return "java";
}
File java = new File(javaHome, "bin/java");
return IO.absolutePath(java);
}
/**
* launch a framework internally. I.e. do not start a separate process.
*/
static Pattern IGNORE = Pattern.compile("org(/|\\.)osgi(/|\\.).resource.*");
public int start(ClassLoader parent) throws Exception {
prepare();
// Intermediate class loader to not load osgi framework packages
// from bnd's loader. Unfortunately, bnd uses some osgi classes
// itself that would unnecessarily constrain the framework.
ClassLoader fcl = new ClassLoader(parent) {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (IGNORE.matcher(name)
.matches())
throw new ClassNotFoundException();
return super.loadClass(name, resolve);
}
};
// Load the class that would have gone to the class path
// i.e. the framework etc.
List<URL> cp = new ArrayList<>();
for (String path : getClasspath()) {
cp.add(new File(path).toURI()
.toURL());
}
@SuppressWarnings("resource")
URLClassLoader cl = new URLClassLoader(cp.toArray(new URL[0]), fcl);
String[] args = getRunProgramArgs().toArray(new String[0]);
Class<?> main = cl.loadClass(getMainTypeName());
return invoke(main, args);
}
protected int invoke(Class<?> main, String args[]) throws Exception {
throw new UnsupportedOperationException();
}
/**
* Is called after the process exists. Can you be used to cleanup the
* properties file.
*/
public void cleanup() {
// do nothing by default
}
protected void reportResult(int result) {
switch (result) {
case OK :
logger.debug("Command terminated normal {}", java);
break;
case TIMEDOUT :
project.error("Launch timedout: %s", java);
break;
case ERROR :
project.error("Launch errored: %s", java);
break;
case WARNING :
project.warning("Launch had a warning %s", java);
break;
default :
project.error("Exit code remote process %d: %s", result, java);
break;
}
}
public void setTimeout(long timeout, TimeUnit unit) {
this.timeout = unit.convert(timeout, TimeUnit.MILLISECONDS);
}
public long getTimeout() {
return this.timeout;
}
public void cancel() throws Exception {
java.cancel();
}
public Map<String, ? extends Map<String, String>> getSystemPackages() {
return runsystempackages.asMapMap();
}
public String getSystemCapabilities() {
return runsystemcapabilities.isEmpty() ? null : runsystemcapabilities.toString();
}
public Parameters getSystemCapabilitiesParameters() {
return runsystemcapabilities;
}
public void setKeep(boolean keep) {
this.keep = keep;
}
public boolean isKeep() {
return keep;
}
@Override
public void setTrace(boolean level) {
this.trace = level;
}
public boolean getTrace() {
return this.trace;
}
/**
* Should be called when all the changes to the launchers are set. Will
* calculate whatever is necessary for the launcher.
*
* @throws Exception
*/
public abstract void prepare() throws Exception;
public Project getProject() {
return project;
}
public boolean addActivator(String e) {
return activators.add(e);
}
public Collection<String> getActivators() {
return Collections.unmodifiableCollection(activators);
}
/**
* Either NONE or SERVICES to indicate how the remote end launches. NONE
* means it should not use the classpath to run a framework. This likely
* requires some dummy framework support. SERVICES means it should load the
* framework from the claspath.
*/
public int getRunFramework() {
return framework;
}
public void setRunFramework(int n) {
assert n == NONE || n == SERVICES;
this.framework = n;
}
/**
* Add the specification for a set of bundles the runpath if it does not
* already is included. This can be used by subclasses to ensure the proper
* jars are on the classpath.
*
* @param defaultSpec The default spec for default jars
*/
public void addDefault(String defaultSpec) throws Exception {
Collection<Container> deflts = project.getBundles(Strategy.HIGHEST, defaultSpec, null);
for (Container c : deflts)
addClasspath(c);
}
/**
* Create a self executable.
*/
public Jar executable() throws Exception {
throw new UnsupportedOperationException();
}
public File getCwd() {
return cwd;
}
public void setCwd(File cwd) {
this.cwd = cwd;
}
public String getRunJdb() {
return project.getProperty(Constants.RUNJDB);
}
public Map<String, String> getRunEnv() {
String runenv = project.getProperty(Constants.RUNENV);
if (runenv != null) {
return OSGiHeader.parseProperties(runenv);
}
return Collections.emptyMap();
}
public static interface NotificationListener {
void notify(NotificationType type, String notification);
}
public static enum NotificationType {
ERROR,
WARNING,
INFO;
}
public void registerForNotifications(NotificationListener listener) {
listeners.add(listener);
}
public Set<NotificationListener> getNotificationListeners() {
return Collections.unmodifiableSet(listeners);
}
/**
* Set the stderr and stdout streams for the output process. The debugged
* process must append its output (i.e. write operation in the process under
* debug) to the given appendables.
*
* @param out std out
* @param err std err
*/
public void setStreams(Appendable out, Appendable err) {
this.out = out;
this.err = err;
}
/**
* Write text to the debugged process as if it came from stdin.
*
* @param text the text to write
* @throws Exception
*/
public void write(String text) throws Exception {
}
/**
* Get the run sessions. If this return null, then launch on this object
* should be used, otherwise each returned object provides a remote session.
*
* @throws Exception
*/
public List<? extends RunSession> getRunSessions() throws Exception {
return null;
}
/**
* Utility to calculate the final framework properties from settings
*/
/**
* This method should go to the ProjectLauncher
*
* @throws Exception
*/
public void calculatedProperties(Map<String, Object> properties) throws Exception {
if (!keep)
properties.put(org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN,
org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
if (!runsystemcapabilities.isEmpty())
properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA,
runsystemcapabilities.toString());
if (!runsystempackages.isEmpty())
properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, runsystempackages.toString());
}
} |
package pl.pwr.hiervis.ui;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.Supplier;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import pl.pwr.hiervis.util.GridBagConstraintsBuilder;
import pl.pwr.hiervis.util.SwingUIUtils;
import javax.swing.SwingConstants;
@SuppressWarnings("serial")
public class OperationProgressFrame extends JDialog
{
private JLabel status;
private JProgressBar progressBar;
private JButton button;
private Supplier<Integer> progressCallback;
private Supplier<String> statusCallback;
private Timer timer;
public OperationProgressFrame( Window owner, String title )
{
super( owner, title );
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
setMinimumSize( new Dimension( 200, 100 ) );
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 0, 0 };
layout.rowHeights = new int[] { 0, 0, 0 };
layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
layout.rowWeights = new double[] { 1.0, 1.0, 0.0 };
getContentPane().setLayout( layout );
GridBagConstraintsBuilder builder = new GridBagConstraintsBuilder();
status = new JLabel();
status.setHorizontalAlignment( SwingConstants.CENTER );
getContentPane().add( status, builder.insets( 5, 5, 5, 5 ).position( 0, 0 ).fillHorizontal().anchorSouth().build() );
progressBar = new JProgressBar();
progressBar.setIndeterminate( true );
getContentPane().add( progressBar, builder.insets( 0, 5, 5, 5 ).position( 0, 1 ).fillHorizontal().anchorNorth().build() );
button = new JButton( "Abort" );
button.setEnabled( false );
getContentPane().add( button, builder.anchorCenter().insets( 0, 5, 5, 5 ).position( 0, 2 ).build() );
SwingUIUtils.addCloseCallback( this, () -> button.doClick() );
}
/**
* Sets the operation to execute when the user presses the 'Abort' button.
*
* @param abortOperation
* the operation to perform when the 'Abort' button is pressed.
* If null, the button is disabled.
*/
public void setAbortOperation( ActionListener abortOperation )
{
ActionListener[] listeners = button.getActionListeners();
for ( ActionListener listener : listeners )
button.removeActionListener( listener );
if ( abortOperation != null )
button.addActionListener( abortOperation );
button.setEnabled( abortOperation != null );
}
/**
* Sets the callback that supplies an integer representing the operation's progress.
*
* @param progressSupplier
* a callback that provides an integer, which represents the operation's progress.
* If null, the progress bar is made indeterminate.
*/
public void setProgressUpdateCallback( Supplier<Integer> progressSupplier )
{
if ( progressSupplier == null && statusCallback == null ) {
cleanupTimer();
}
progressBar.setIndeterminate( progressSupplier == null );
progressCallback = progressSupplier;
}
public void setStatusUpdateCallback( Supplier<String> statusSupplier )
{
if ( statusSupplier == null && progressCallback == null ) {
cleanupTimer();
}
statusCallback = statusSupplier;
}
/**
* Sets the interval at which to poll the {@code updateCallback} and update the progress bar.
*
* @param intervalMs
* the interval, in milliseconds. If value is less than or equal to 0, polling is disabled.
*/
public void setProgressPollInterval( int intervalMs )
{
cleanupTimer();
if ( intervalMs > 0 ) {
timer = new Timer( true );
TimerTask tt = new TimerTask() {
@Override
public void run()
{
updateProgressLater();
}
};
timer.scheduleAtFixedRate( tt, 0, intervalMs );
}
}
/**
* Schedules an update, so that the progress bar displays the most recent progress value.
* If {@code updateCallback} is not set, this method does nothing.
*/
public void updateProgressLater()
{
// The actual update call is deferred and performed on the main thread,
// so updateCallback's value *might* have changed.
if ( progressCallback != null || statusCallback != null ) {
SwingUtilities.invokeLater(
() -> {
if ( progressCallback != null ) {
int value = progressCallback.get();
if ( value < 0 ) {
progressBar.setIndeterminate( true );
}
else {
progressBar.setValue( value );
}
}
if ( statusCallback != null ) {
status.setText( statusCallback.get() );
}
}
);
}
}
private void cleanupTimer()
{
if ( timer != null ) {
timer.cancel();
timer = null;
}
}
@Override
public void dispose()
{
super.dispose();
cleanupTimer();
}
} |
import java.applet.Applet;
import java.util.ArrayList;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSchException;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import java.util.Iterator;
import java.util.Map.Entry;
import com.google.gson.JsonPrimitive;
import java.io.Writer;
import java.io.OutputStreamWriter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.swing.JDialog;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
/*
* static class to hold
* twister resources
*/
public class Repository{
private static ArrayList <Item> suite = new ArrayList <Item> ();//suite list
private static ArrayList<Item> suitetest = new ArrayList<Item>();//test suite list generated
private static String bar = System.getProperty("file.separator");//System specific file.separator
private static ArrayList<String> logs = new ArrayList<String>();//logs tracked by twister framwork
public static String[] columnNames;
public static Window window;//main window displayed if twister is running local
public static ChannelSftp c;//main sftp connection used by Twister
public static String temp,TWISTERINI, USERHOME, REMOTECONFIGDIRECTORY, HTTPSERVERPORT, CENTRALENGINEPORT, RESOURCEALLOCATORPORT, REMOTEDATABASECONFIGPATH, REMOTEDATABASECONFIGFILE, REMOTEEMAILCONFIGPATH, REMOTEEMAILCONFIGFILE,CONFIGDIRECTORY, USERSDIRECTORY, XMLDIRECTORY, TESTSUITEPATH, LOGSPATH ,XMLREMOTEDIR, REMOTEUSERSDIRECTORY, REMOTEEPIDDIR, REMOTEHARDWARECONFIGDIRECTORY;
public static Image passicon,testbedicon,porticon,suitaicon, tcicon, propicon, failicon, passwordicon, playicon, stopicon, pauseicon, background,notexecicon,pendingicon,skipicon,stoppedicon,timeouticon,waiticon,workingicon,moduleicon,deviceicon,addsuitaicon,removeicon,vlcclient,vlcserver,switche,flootw,rack150,rack151,rack152,switche2,inicon,outicon,baricon;
public static boolean run = true;//signal that Twister is not closing
public static boolean applet; //keeps track if twister is run from applet or localy
public static IntroScreen intro;
public static String user,host,password;
private static ArrayList <String []> databaseUserFields = new ArrayList<String[]>();
public static int LABEL = 0;
public static int ID = 1;
public static int SELECTED = 2;
public static int MANDATORY = 3;
public static int ELEMENTSNR = 4;
private static XmlRpcClient client;
private static JsonObject inifile;//json structure of conf file saved localy
private static JsonObject editors, looks;//editors saved by user localy
private static String[] lookAndFeels;
private static Applet container;
/*
* repository initialization method
* applet - if it is initialized from applet
* host - server for twister location
* container - applet or null
*/
public static void initialize(final boolean applet,String host,Applet container){
Repository.container = container;
/*
* temp folder creation to hold
* all the needed twister files localy
*/
try{
// File g = File.createTempFile("tmp","");
// temp = g.getParent();
// g.delete();
temp = System.getProperty("user.home")+bar+".twister" ;
File g1 = new File(temp);
if(g1.mkdir()){
System.out.println(temp+" succesfuly created");}
else System.out.println(temp+" could not be created ");
g1 = new File(temp+bar+host);
if(g1.mkdir()){
System.out.println(temp+bar+host+" succesfuly created");}
else System.out.println(temp+bar+host+" could not be created ");
temp = g1.getCanonicalPath();}
catch(Exception e){
System.out.println("Could not retrieve Temp directory for this OS");
e.printStackTrace();}
System.out.println("Temp directory where Twister Directory is created: "+temp);
File file = new File(Repository.temp+bar+"Twister");
File twisterhome = new File(System.getProperty("user.home")+bar+".twister");
/*
* if file was not deleted on previous
* Twister exit, delete it now
*/
if(file.exists()){
if(Window.deleteTemp(file))System.out.println(Repository.temp+bar+"Twister deleted successfull");
else System.out.println("Could not delete: "+Repository.temp+bar+"Twister");}
if(!twisterhome.exists()){
try{if(twisterhome.mkdir())System.out.println(twisterhome.getCanonicalPath()+" succesfuly created");
else System.out.println("Could not create "+twisterhome.getCanonicalPath());}
catch(Exception e){
System.out.println("Could not create "+System.getProperty("user.home")+bar+".twister");
e.printStackTrace();}}
/*
* twiste configuration file
*/
try{File twisterini = new File(twisterhome.getCanonicalPath()+bar+"twister.conf");
TWISTERINI = twisterhome.getCanonicalPath()+bar+"twister.conf";
if(!twisterini.exists()){// if it does not exist, create one from scratch
if(new File(twisterhome.getCanonicalPath()+bar+"twister.conf").createNewFile()){
JsonObject root = new JsonObject();
JsonObject array =new JsonObject();
array.addProperty("Embedded", "embedded");
array.addProperty("DEFAULT", "Embedded");
JsonObject array2 =new JsonObject();
array2.addProperty("NimbusLookAndFeel", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
array2.addProperty("MetalLookAndFeel", "javax.swing.plaf.metal.MetalLookAndFeel");
array2.addProperty("MotifLookAndFeel", "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
array2.addProperty("WindowsLookAndFeel", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
array2.addProperty("JGoodiesWindowsLookAndFeel", "com.jgoodies.looks.windows.WindowsLookAndFeel");
array2.addProperty("Plastic3DLookAndFeel", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
array2.addProperty("PlasticXPLookAndFeel", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
array2.addProperty("DEFAULT", "MetalLookAndFeel");
root.add("editors", array);
root.add("looks", array2);
try{FileWriter writer = new FileWriter(TWISTERINI);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
writer.write(gson.toJson(root));
writer.close();}
catch(Exception e){
System.out.println("Could not write default JSon to twister.conf");
e.printStackTrace();}
System.out.println("twister.conf succesfuly created");}
else System.out.println("Could not create twister.conf");}
parseIni(twisterini);}//parse configuration file
catch(Exception e){e.printStackTrace();}
Repository.host = host;
System.out.println("Setting sftp server to :"+host);
intro = new IntroScreen();//display intro screen
intro.setVisible(true);
intro.setStatus("Started initialization");
intro.repaint();
Repository.applet = applet;
if(applet)System.out.println("Twister running from applet");
else System.out.println("Twister running from Main");
try{if(!applet){
/*
* if it did not start from applet
* the resources must be loaded from local pc
*/
InputStream in;
in = Repository.class.getResourceAsStream("Icons"+bar+"background.png");
background = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"vlcclient.png");
vlcclient = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"vlcserver.png");
vlcserver = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"switch.png");
switche = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"twisterfloodlight.png");
flootw = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"150.png");
rack150 = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"151.png");
rack151 = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"152.png");
rack152 = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"switch.jpg");
switche2 = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"in.png");
inicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"out.png");
outicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"bar.png");
baricon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"port.png");
porticon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"deleteicon.png");
removeicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"addsuita.png");
addsuitaicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"device.png");
deviceicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"module.png");
moduleicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"tc.png");
Repository.tcicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"suita.png");
Repository.suitaicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"prop.png");
Repository.propicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"fail.png");
Repository.failicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"pass.png");
Repository.passicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"stop.png");
Repository.stopicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"play.png");
Repository.playicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"notexec.png");
Repository.notexecicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"pending.png");
Repository.pendingicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"skip.png");
Repository.skipicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"stopped.png");
Repository.stoppedicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"timeout.png");
Repository.timeouticon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"waiting.png");
Repository.waiticon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"passwordicon.png");
Repository.passwordicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"working.png");
Repository.workingicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"pause.png");
Repository.pauseicon = new ImageIcon(ImageIO.read(in)).getImage();
in = Repository.class.getResourceAsStream("Icons"+bar+"testbed.png");
Repository.testbedicon = new ImageIcon(ImageIO.read(in)).getImage();
in.close();}
if(userpassword()){
/*
* create directory structure
* for twister resources localy
*/
System.out.println("Authentication succeeded");
if(new File(temp+bar+"Twister").mkdir())System.out.println(temp+bar+"Twister"+" folder successfully created");
else System.out.println("Could not create "+temp+bar+"Twister"+" folder");
if(new File(temp+bar+"Twister"+bar+"HardwareConfig").mkdir())System.out.println(temp+bar+"Twister"+bar+"HardwareConfig folder successfully created");
else System.out.println("Could not create "+temp+bar+"Twister"+bar+"HardwareConfig folder");
if(new File(temp+bar+"Twister"+bar+"XML").mkdir())System.out.println(temp+bar+"Twister"+bar+"XML folder successfully created");
else System.out.println("Could not create "+temp+bar+"Twister"+bar+"XML folder");
if(new File(temp+bar+"Twister"+bar+"Users").mkdir())System.out.println(temp+bar+"Twister"+bar+"Users folder successfully created");
else System.out.println("Could not create "+temp+bar+"Twister"+bar+"Users folder");
if(new File(temp+bar+"Twister"+bar+"config").mkdir())System.out.println(temp+bar+"Twister"+bar+"config folder successfully created");
else System.out.println("Could not create "+temp+bar+"Twister"+bar+"config folder");
USERSDIRECTORY = Repository.temp+bar+"Twister"+bar+"Users";
CONFIGDIRECTORY = Repository.temp+bar+"Twister"+bar+"config";
intro.setStatus("Started to parse the config");
intro.addPercent(0.035);
intro.repaint();
parseConfig();
/*
* XmlRpc main connection used by Twister framework
*/
try{XmlRpcClientConfigImpl configuration = new XmlRpcClientConfigImpl();
configuration.setServerURL(new URL("http://"+Repository.host+":"+Repository.getCentralEnginePort()));
client = new XmlRpcClient();
client.setConfig(configuration);
System.out.println("Client initialized: "+client);}
catch(Exception e){System.out.println("Could not conect to "+Repository.host+" :"+Repository.getCentralEnginePort()+"for client initialization");}
intro.setStatus("Finished parsing the config");
intro.addPercent(0.035);
intro.repaint();
parseDBConfig(Repository.REMOTEDATABASECONFIGFILE,true);
window = new Window(applet,container);
parseEmailConfig(Repository.REMOTEEMAILCONFIGFILE,true);}
else{
/*
* if login is not scucces remove temp folder
* and exit application
*/
if(Window.deleteTemp(file))System.out.println(Repository.temp+bar+"Twister deleted successfull");
else System.out.println("Could not delete: "+Repository.temp+bar+"Twister");
intro.dispose();
run = false;
if(!applet)System.exit(0);}}
catch(Exception e){e.printStackTrace();}}
/*
* set UI Look based on
* user selection
*/
public static void setUILook(final String look){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
System.out.println("Setting UI: "+look);
try{UIManager.setLookAndFeel(Repository.getLooks().get(look).getAsString());
if(applet){SwingUtilities.updateComponentTreeUI(container);}
else{SwingUtilities.updateComponentTreeUI(window);}}
catch(Exception e){e.printStackTrace();}}});}
/*
* attempt to connect with sftp to server
*/
public static boolean userpassword(){
boolean passed = false;
while(!passed){
try{JTextField user1 = new JTextField();
JPasswordField password1 = new JPasswordField();
JComboBox combo = new JComboBox();
try{populateLookAndFeels();
int index = populateCombo(combo,lookAndFeels);
if(index>-1)combo.setSelectedIndex(index);}
catch(Exception e){
System.out.println("Error: No LooksAndFeels set");
e.printStackTrace();}
JPanel p = getPasswordPanel(user1,password1,combo);
int resp = (Integer)CustomDialog.showDialog(p,JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, intro, "User & Password",new ImageIcon(Repository.getPasswordIcon()));
if(resp == JOptionPane.OK_OPTION){
System.out.println("Attempting to connect to: "+host+" with user: "+user1.getText()+" and password: "+password1.getPassword());
JSch jsch = new JSch();
user = user1.getText();
Session session = jsch.getSession(user, host, 22);
Repository.password = new String(password1.getPassword());
session.setPassword(new String(password1.getPassword()));
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
c = (ChannelSftp)channel;
try{USERHOME = c.pwd();}
catch(Exception e){System.out.println("ERROR: Could not retrieve remote user home directory");}
REMOTECONFIGDIRECTORY = USERHOME+"/twister/config/";
passed = true;
setUILook(combo.getSelectedItem().toString());}
else return false;}
catch(JSchException ex){
if(ex.toString().indexOf("Auth fail")!=-1)System.out.println("wrong user and/or password");
else{ex.printStackTrace();
System.out.println("Could not connect to server");}}}
return true;}
/*
* method used to reset database config
*/
public static void resetDBConf(String filename,boolean server){
databaseUserFields.clear();
System.out.println("Reparsing "+filename);
parseDBConfig(filename,server);
window.mainpanel.p1.suitaDetails.restart(databaseUserFields);}
/*
* method used to reset Email config
*/
public static void resetEmailConf(String filename,boolean server){
System.out.println("Reparsing "+filename);
parseEmailConfig(filename,server);}
/*
* method to get database config file
* name - file name
* fromserver - if from server(true) else from local temp folder
*/
public static File getDBConfFile(String name,boolean fromServer){
File file = new File(temp+bar+"Twister"+bar+"config"+bar+name);
if(fromServer){
InputStream in = null;
try{c.cd(Repository.REMOTEDATABASECONFIGPATH);}
catch(Exception e){System.out.println("Could not get :"+Repository.REMOTEDATABASECONFIGPATH);}
System.out.print("Getting "+name+" as database config file.... ");
try{in = c.get(name);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
BufferedWriter writer = null;
String line;
try{writer = new BufferedWriter(new FileWriter(file));
while ((line=bufferedReader.readLine())!= null){
writer.write(line);
writer.newLine();}
bufferedReader.close();
writer.close();
inputStreamReader.close();
in.close();
System.out.println("successfull");}
catch(Exception e){
System.out.println("failed");
e.printStackTrace();}}
catch(Exception e){System.out.println("Could not get :"+name+" from: "+Repository.REMOTEDATABASECONFIGPATH+" as database config file");}}
return file;}
/*
* method to get Email config file
* name - file name
* fromserver - if from server(true) else from local temp folder
*/
public static File getEmailConfFile(String name,boolean fromServer){
File file = new File(temp+bar+"Twister"+bar+"config"+bar+name);
if(fromServer){
InputStream in = null;
try{c.cd(Repository.REMOTEEMAILCONFIGPATH);}
catch(Exception e){System.out.println("Could not get :"+Repository.REMOTEEMAILCONFIGPATH);}
System.out.print("Getting "+name+" as email config file.... ");
try{in = c.get(name);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
BufferedWriter writer = null;
String line;
try{writer = new BufferedWriter(new FileWriter(file));
while ((line=bufferedReader.readLine())!= null){
writer.write(line);
writer.newLine();}
bufferedReader.close();
writer.close();
inputStreamReader.close();
in.close();
System.out.println("successfull");}
catch(Exception e){
System.out.println("failed");
e.printStackTrace();}}
catch(Exception e){System.out.println("Could not get :"+name+" from: "+Repository.REMOTEEMAILCONFIGPATH+" as email config file");}}
return file;}
/*
* parse database config file
* name - file name
* fromserver - true - false
*/
public static DefaultMutableTreeNode parseDBConfig(String name,boolean fromServer){
File dbConf = getDBConfFile(name,fromServer);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
try{DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(dbConf);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("table_structure");
for(int i=0;i<nodeLst.getLength();i++){
Element tablee = (Element)nodeLst.item(i);
NodeList fields = tablee.getElementsByTagName("field");
DefaultMutableTreeNode table = new DefaultMutableTreeNode(tablee.getAttribute("name"));
for(int j=0;j<fields.getLength();j++){
Element fielde = (Element)fields.item(j);
DefaultMutableTreeNode field = new DefaultMutableTreeNode(fielde.getAttribute("Field"));
table.add(field);}
root.add(table);}
nodeLst = doc.getElementsByTagName("twister_user_defined");
Element tablee = (Element)nodeLst.item(0);
NodeList fields = tablee.getElementsByTagName("field_section");
tablee = (Element)fields.item(0);
fields = tablee.getElementsByTagName("field");
for(int i=0;i<fields.getLength();i++){
tablee = (Element)fields.item(i);
if(tablee.getAttribute("GUIDefined").equals("true")){
String field [] = new String[ELEMENTSNR];
field[0]=tablee.getAttribute("Label");
if(field[0]==null){
System.out.println("Warning, no Label element in field tag in db.xml at filed nr: "+i);
field[0]="";}
field[1]=tablee.getAttribute("ID");
if(field[1]==null){
System.out.println("Warning, no ID element in field tag in db.xml at filed nr: "+i);
field[1]="";}
field[2]=tablee.getAttribute("Type");
if(field[2]==null){
System.out.println("Warning, no Type element in field tag in db.xml at filed nr: "+i);
field[2]="";}
else if (field[2].equals("UserSelect"))field[2] ="true";
else field[2] = "false";
field[3]=tablee.getAttribute("Mandatory");
if(field[3]==null){
System.out.println("Warning, no Mandatory element in field tag in db.xml at filed nr: "+i);
field[3]="";}
databaseUserFields.add(field);}}}
catch(Exception e){
try{System.out.println("Could not parse batabase XML file: "+dbConf.getCanonicalPath());}
catch(Exception ex){
System.out.println("There is a problem with "+name+" file");
ex.printStackTrace();}
e.printStackTrace();}
return root;}
/*
* parse email config file
*/
public static void parseEmailConfig(String name,boolean fromServer){
File dbConf = getEmailConfFile(name,fromServer);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(dbConf);
doc.getDocumentElement().normalize();
window.mainpanel.p4.emails.setCheck(Boolean.parseBoolean(getTagContent(doc, "Enabled")));
String smtppath = getTagContent(doc, "SMTPPath");
window.mainpanel.p4.emails.setIPName(smtppath.split(":")[0]);
window.mainpanel.p4.emails.setPort(smtppath.split(":")[1]);
window.mainpanel.p4.emails.setUser(getTagContent(doc, "SMTPUser"));
window.mainpanel.p4.emails.setFrom(getTagContent(doc, "From"));
window.mainpanel.p4.emails.setEmails(getTagContent(doc, "To"));
if(!getTagContent(doc, "SMTPPwd").equals("")){window.mainpanel.p4.emails.setPassword("****");}
window.mainpanel.p4.emails.setMessage(getTagContent(doc, "Message"));
window.mainpanel.p4.emails.setSubject(getTagContent(doc, "Subject"));}
catch(Exception e){e.printStackTrace();}}
/*
* parse main fwmconfig file
*/
public static void parseConfig(){
try{InputStream in = null;
byte[] data = new byte[100];
int nRead;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
OutputStream out=null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
BufferedWriter writer=null;
File file;
String line = null;
String name = null;
try{c.cd(USERHOME+"/twister/config/");}
catch(Exception e){System.out.println("Could not get :"+USERHOME+"/twister/config/");
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE,Repository.window, "Warning", "Could not get :"+USERHOME+"/twister/config/");
if(Window.deleteTemp(new File(Repository.temp+bar+"Twister")))System.out.println(Repository.temp+bar+"Twister deleted successfull");
else System.out.println("Could not delete: "+Repository.temp+bar+"Twister");
intro.dispose();
run = false;
if(!applet)System.exit(0);}
try{System.out.println("fwmconfig.xml size on sftp: "+c.lstat("fwmconfig.xml").getSize()+" bytes");
in = c.get("fwmconfig.xml");}
catch(Exception e){
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, Repository.window, "Warning","Could not get fwmconfig.xml from "+c.pwd()+" creating a blank one.");
System.out.println("Could not get fwmconfig.xml from "+c.pwd()+" creating a blank one.");
ConfigFiles.saveXML(true);
in = c.get("fwmconfig.xml");}
inputStreamReader = new InputStreamReader(in);
bufferedReader = new BufferedReader(inputStreamReader);
file = new File(temp+bar+"Twister"+bar+"config"+bar+"fwmconfig.xml");
writer = new BufferedWriter(new FileWriter(file));
while((line=bufferedReader.readLine())!= null){
writer.write(line);
writer.newLine();}
bufferedReader.close();
writer.close();
inputStreamReader.close();
in.close();
System.out.println("fwmconfig.xml local size: "+file.length()+" bytes");
String usersdir="";
intro.setStatus("Finished getting fwmconfig");
intro.addPercent(0.035);
intro.repaint();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(Repository.getFwmConfig());
doc.getDocumentElement().normalize();
LOGSPATH = getTagContent(doc,"LogsPath");
if(doc.getElementsByTagName("LogFiles").getLength()==0)System.out.println("LogFiles tag not found in fwmconfig");
else{logs.add(getTagContent(doc,"logRunning"));
logs.add(getTagContent(doc,"logDebug"));
logs.add(getTagContent(doc,"logSummary"));
logs.add(getTagContent(doc,"logTest"));
logs.add(getTagContent(doc,"logCli"));}
HTTPSERVERPORT = getTagContent(doc,"HttpServerPort");
CENTRALENGINEPORT = getTagContent(doc,"CentralEnginePort");
RESOURCEALLOCATORPORT = getTagContent(doc,"ResourceAllocatorPort");
usersdir = getTagContent(doc,"UsersPath");
REMOTEUSERSDIRECTORY = usersdir;
XMLREMOTEDIR = getTagContent(doc,"MasterXMLTestSuite");
XMLDIRECTORY = Repository.temp+bar+"Twister"+bar+"XML"+bar+XMLREMOTEDIR.split("/")[XMLREMOTEDIR.split("/").length-1];
REMOTEEPIDDIR = getTagContent(doc,"EPIdsFile");
REMOTEDATABASECONFIGFILE = getTagContent(doc,"DbConfigFile");
String [] path = REMOTEDATABASECONFIGFILE.split("/");
StringBuffer result = new StringBuffer();
if (path.length > 0) {
for (int i=0; i<path.length-1; i++){
result.append(path[i]);
result.append("/");}}
REMOTEDATABASECONFIGPATH = result.toString();
REMOTEDATABASECONFIGFILE = path[path.length-1];
REMOTEEMAILCONFIGFILE = getTagContent(doc,"EmailConfigFile");
path = REMOTEEMAILCONFIGFILE.split("/");
result = new StringBuffer();
if (path.length > 0) {
for (int i=0; i<path.length-1; i++){
result.append(path[i]);
result.append("/");}}
REMOTEEMAILCONFIGPATH = result.toString();
REMOTEEMAILCONFIGFILE = path[path.length-1];
TESTSUITEPATH = getTagContent(doc,"TestCaseSourcePath");
REMOTEHARDWARECONFIGDIRECTORY = getTagContent(doc,"HardwareConfig");}
catch(Exception e){e.printStackTrace();}
intro.setStatus("Finished initializing variables fwmconfig");
intro.addPercent(0.035);
intro.repaint();
intro.setStatus("Started getting users xml");
intro.addPercent(0.035);
intro.repaint();
try{c.cd(usersdir);}
catch(Exception e){System.out.println("Could not get to "+usersdir+"on sftp");}
int subdirnr = usersdir.split("/").length-1;
int size ;
try{size= c.ls(usersdir).size();}
catch(Exception e){
System.out.println("No suites xml");
size=0;}
for(int i=0;i<size;i++){
name = ((LsEntry)c.ls(usersdir).get(i)).getFilename();
if(name.split("\\.").length==0)continue;
if(name.toLowerCase().indexOf(".xml")==-1)continue;
System.out.print("Getting "+name+" ....");
in = c.get(name);
inputStreamReader = new InputStreamReader(in);
bufferedReader = new BufferedReader(inputStreamReader);
file = new File(temp+bar+"Twister"+bar+"Users"+bar+name);
writer = new BufferedWriter(new FileWriter(file));
while ((line=bufferedReader.readLine())!= null){
writer.write(line);
writer.newLine();}
bufferedReader.close();
writer.close();
inputStreamReader.close();
in.close();
System.out.println("successfull");}
intro.setStatus("Finished getting users xml");
intro.addPercent(0.035);
intro.repaint();
String dir = Repository.getXMLRemoteDir();
String [] path = dir.split("/");
StringBuffer result = new StringBuffer();
if (path.length > 0) {
for (int i=0; i<path.length-2; i++){
result.append(path[i]);
result.append("/");}}
intro.setStatus("Finished writing xml path");
intro.addPercent(0.035);
intro.repaint();
int length = 0;
try{length = c.ls(result.toString()+path[path.length-2]).size();}
catch(Exception e){System.out.println("Could not get "+result.toString()+dir);}
if(length>2){
intro.setStatus("Started looking for xml file");
intro.addPercent(0.035);
intro.repaint();
intro.setStatus("Started getting xml file");
intro.addPercent(0.035);
intro.repaint();
System.out.println("XMLREMOTEDIR: "+XMLREMOTEDIR);
in = c.get(XMLREMOTEDIR);
data = new byte[900];
buffer = new ByteArrayOutputStream();
while ((nRead = in.read(data, 0, data.length)) != -1){buffer.write(data, 0, nRead);}
intro.setStatus("Finished reading xml ");
intro.addPercent(0.035);
intro.repaint();
buffer.flush();
out = new FileOutputStream(temp+bar+"Twister"+bar+"XML"+bar+XMLREMOTEDIR.split("/")[XMLREMOTEDIR.split("/").length-1]);
intro.setStatus("Started writing xml file");
intro.addPercent(0.035);
intro.repaint();
buffer.writeTo(out);
out.close();
buffer.close();
in.close();}
intro.setStatus("Finished writing xml");
intro.addPercent(0.035);
intro.repaint();}
catch(Exception e){e.printStackTrace();}}
/*
* method to get tag content from xml
* doc - xml document
* tag - tag name
*/
public static String getTagContent(Document doc, String tag){
NodeList nodeLst = doc.getElementsByTagName(tag);
if(nodeLst.getLength()==0)System.out.println("tag "+tag+" not found in "+doc.getDocumentURI());
Node fstNode = nodeLst.item(0);
Element fstElmnt = (Element)fstNode;
NodeList fstNm = fstElmnt.getChildNodes();
String temp;
try{temp = fstNm.item(0).getNodeValue().toString();}
catch(Exception e){
System.out.println(tag+" empty");
temp = "";}
return temp;}
/*
* parser for conf twister file
*/
public static void parseIni(File ini){
try{FileInputStream in = new FileInputStream(ini);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer b=new StringBuffer("");
String line;
try{while ((line=bufferedReader.readLine())!= null){b.append(line);}
bufferedReader.close();
inputStreamReader.close();
in.close();}
catch(Exception e){e.printStackTrace();}
line = b.toString();
JsonElement jelement = new JsonParser().parse(line);
inifile = jelement.getAsJsonObject();
editors = inifile.getAsJsonObject("editors");
looks = inifile.getAsJsonObject("looks");
System.out.println("Editors: "+editors.toString());}
catch(Exception e){
System.out.print("Could not parse ini file: ");
try{System.out.println(ini.getCanonicalPath());}
catch(Exception ex){ex.printStackTrace();}
e.printStackTrace();}}
/*
* method to add suite to suite list
*/
public static void addSuita(Item s){
suite.add(s);}
/*
* method to get suite from suite list
* s - suite index in list
*/
public static Item getSuita(int s){
return suite.get(s);}
/*
* method to get suite list size
*/
public static int getSuiteNr(){
return suite.size();}
/*
* method to get Database User Fields
* set from twister
*/
public static ArrayList<String[]> getDatabaseUserFields(){
return databaseUserFields;}
/*
* clear all suite from test suite list
*/
public static void emptyTestRepository(){
suitetest.clear();}
/*
* clear the list of logs tracked by Twister
*/
public static void emptyLogs(){
logs.clear();}
/*
* method to get config file from local pc
*/
public static File getFwmConfig(){
return new File(temp+bar+"Twister"+bar+"config"+bar+"fwmconfig.xml");}
/*
* users directory from temp folder on local pc
*/
public static String getUsersDirectory(){
return USERSDIRECTORY;}
/*
* Ep directory from server
*/
public static String getRemoteEpIdDir(){
return REMOTEEPIDDIR;}
/*
* Users directory from server
*/
public static String getRemoteUsersDirectory(){
return REMOTEUSERSDIRECTORY;}
/*
* CentralEnginePort set by fwmconfig file
*/
public static String getCentralEnginePort(){
return CENTRALENGINEPORT;}
/*
* ResourceAllocatorPort set by fwmconfig file
*/
public static String getResourceAllocatorPort(){
return RESOURCEALLOCATORPORT;}
/*
* test suite xml directory from server
*/
public static String getXMLRemoteDir(){
return XMLREMOTEDIR;}
/*
* suite list from repository
*/
public static ArrayList<Item> getSuite(){
return suite;}
/*
* test suite list size from repository
*/
public static int getTestSuiteNr(){
return suitetest.size();}
/*
* local config directory from temp
*/
public static String getConfigDirectory(){
return CONFIGDIRECTORY;}
/*
* add suite to test suite list
*/
public static void addTestSuita(Item suita){
suitetest.add(suita);}
/*
* HTTPServerPort set by fwmconfig file
*/
public static String getHTTPServerPort(){
return HTTPSERVERPORT;}
/*
* method to get suite from test suite list
* i - suite index in test suite list
*/
public static Item getTestSuita(int i){
return suitetest.get(i);}
/*
* test suite path on server
*/
public static String getTestSuitePath(){
return TESTSUITEPATH;}
/*
* empty suites list in Repository
*/
public static void emptySuites(){
suite.clear();}
/*
* test suite xml local directory
*/
public static String getTestXMLDirectory(){
return XMLDIRECTORY;}
/*
* declare posible looksAndFeel
*/
private static void populateLookAndFeels(){
JsonObject looks = Repository.getLooks();
int length = looks.entrySet().size();
Iterator iter = looks.entrySet().iterator();
Entry entry;
String [] vecresult;
if(looks.get("DEFAULT")!=null)lookAndFeels = new String[length-1];
else lookAndFeels = new String[length];
int index = 0;
for(int i=0;i<length;i++){
entry = (Entry)iter.next();
if(entry.getKey().toString().equals("DEFAULT"))continue;
lookAndFeels[index] = (String)entry.getKey();
index++;}}
/*
*populate lookandfeel cobo
*with looks and feels that are
*available
*/
private static int populateCombo(JComboBox combo,String[]list){
int index = -1;
String name;
System.out.println("list length is: "+list.length);
for(int i=0;i<list.length;i++){
try{Class.forName(getLooks().get(list[i]).getAsString());
combo.addItem(list[i]);
if(Repository.getDefaultLook().equals(list[i])){
index = i;}}
catch(Exception e){continue;}}
return index;}
/*
* panel displayed on
* twister startup for user and password
* input
*/
public static JPanel getPasswordPanel(JTextField jTextField1,JPasswordField jTextField2,final JComboBox combo){
final JCheckBox check = new JCheckBox("Default");
check.setSelected(true);
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
JPanel jPanel1 = new JPanel();
JLabel jLabel3 = new JLabel();
JPanel jPanel2 = new JPanel();
JLabel jLabel4 = new JLabel();
JPanel jPanel5 = new JPanel();
jPanel5.add(combo);
jPanel5.add(check);
jPanel1.setLayout(new java.awt.BorderLayout());
jLabel3.setText("User: ");
jPanel1.add(jLabel3, BorderLayout.CENTER);
p.add(jPanel1);
p.add(jTextField1);
jPanel2.setLayout(new BorderLayout());
jLabel4.setText("Password: ");
jPanel2.add(jLabel4, BorderLayout.CENTER);
p.add(jPanel2);
p.add(jTextField2);
p.add(jPanel5);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(evt.getStateChange() == ItemEvent.SELECTED){
if(Repository.getDefaultLook().equals(evt.getItem().toString())) check.setSelected(true);
else check.setSelected(false);}}});
check.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
if(check.isSelected())Repository.setDefaultLook(combo.getSelectedItem().toString());
else Repository.setDefaultLook("MetalLookAndFeel");}});
return p;}
/*
* Twister icons
*/
public static Image getSuitaIcon(){
return suitaicon;}
public static Image getFailIcon(){
return failicon;}
public static Image getPendingIcon(){
return pendingicon;}
public static Image getWorkingIcon(){
return workingicon;}
public static Image getNotExecIcon(){
return notexecicon;}
public static Image getTimeoutIcon(){
return timeouticon;}
public static Image getSkippedIcon(){
return skipicon;}
public static Image getWaitingIcon(){
return waiticon;}
public static Image getStopIcon(){
return stopicon;}
public static Image getTestBedIcon(){
return testbedicon;}
public static Image getStoppedIcon(){
return stoppedicon;}
public static Image getPassIcon(){
return passicon;}
public static Image getTCIcon(){
return tcicon;}
public static Image getPlayIcon(){
return playicon;}
public static String getBar(){
return bar;}
public static Image getPropertyIcon(){
return propicon;}
public static Image getPasswordIcon(){
return passwordicon;}
/*
* looks saved in conf file
*/
public static JsonObject getLooks(){
return looks;}
/*
* default look name
* saved in json list
*
*/
public static String getDefaultLook(){
return getLooks().get("DEFAULT").getAsJsonPrimitive().getAsString();}
/*
* write default look
* in json list and in local conf *
*/
public static void setDefaultLook(String look){
addLook(new String[]{"DEFAULT",look});
writeJSon();}
/*
* add user defined look to list
* of looks
*/
public static void addLook(String [] look){
getLooks().add(look[0],new JsonPrimitive(look[1]));
writeJSon();}
/*
* editors saved in conf file
*/
public static JsonObject getEditors(){
return editors;}
/*
* delete editor from editors list
* and save file
*/
public static void removeEditor(String editor){
editors.remove(editor);
writeJSon();}
/*
* add user defined editor to list
* of editors
*/
public static void addEditor(String [] editor){
getEditors().add(editor[0],new JsonPrimitive(editor[1]));
writeJSon();}
/*
* default editor name
* saved in json list
*
*/
public static String getDefaultEditor(){
return getEditors().get("DEFAULT").getAsJsonPrimitive().getAsString();}
/*
* write default editor
* in json list and in local conf *
*/
public static void setDefaultEditor(String editor){
addEditor(new String[]{"DEFAULT",editor});
writeJSon();}
/*
* write local conf
* with saved json
*/
public static void writeJSon(){
try{Writer writer = new OutputStreamWriter(new FileOutputStream(TWISTERINI));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(inifile, writer);
writer.close();}
catch(Exception e){
System.out.println("Could not write to local config file");
e.printStackTrace();}}
/*
* logs tracked by twister framwork
*/
public static ArrayList<String> getLogs(){
return logs;}
/*
* RPC connection
*/
public static XmlRpcClient getRPCClient(){
return client;}
/*
* user used on twister server
*/
public static String getUser(){
return user;}} |
package hex.glm;
import hex.ModelMetricsRegressionGLM;
import hex.glm.GLMModel.GLMParameters;
import hex.glm.GLMModel.GLMParameters.Family;
import hex.glm.GLMModel.GLMParameters.Solver;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import water.DKV;
import water.Key;
import water.TestUtil;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.parser.ParseDataset;
import java.io.File;
import java.util.HashMap;
import water.fvec.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GLMBasicTestRegression extends TestUtil {
static Frame _canCarTrain;
static Frame _earinf;
static Frame _weighted;
static Frame _upsampled;
static Vec _merit, _class;
static Frame _prostateTrain;
@BeforeClass
public static void setup() {
stall_till_cloudsize(1);
File f = find_test_file_static("smalldata/glm_test/cancar_logIn.csv");
assert f.exists();
NFSFileVec nfs = NFSFileVec.make(f);
Key outputKey = Key.make("prostate_cat_train.hex");
_canCarTrain = ParseDataset.parse(outputKey, nfs._key);
_canCarTrain.add("Merit", (_merit = _canCarTrain.remove("Merit")).toCategoricalVec());
_canCarTrain.add("Class",(_class = _canCarTrain.remove("Class")).toCategoricalVec());
DKV.put(_canCarTrain._key, _canCarTrain);
f = find_test_file_static("smalldata/glm_test/earinf.txt");
assert f.exists();
nfs = NFSFileVec.make(f);
outputKey = Key.make("earinf.hex");
_earinf = ParseDataset.parse(outputKey, nfs._key);
DKV.put(_earinf._key,_earinf);
f = find_test_file_static("smalldata/glm_test/weighted.csv");
assert f.exists();
nfs = NFSFileVec.make(f);
outputKey = Key.make("weighted.hex");
_weighted = ParseDataset.parse(outputKey, nfs._key);
DKV.put(_weighted._key,_weighted);
f = find_test_file_static("smalldata/glm_test/upsampled.csv");
assert f.exists();
nfs = NFSFileVec.make(f);
outputKey = Key.make("upsampled.hex");
_upsampled = ParseDataset.parse(outputKey, nfs._key);
DKV.put(_upsampled._key,_upsampled);
_prostateTrain = parse_test_file("smalldata/glm_test/prostate_cat_train.csv");
}
@Test public void testWeights() {
GLM job1 = null, job2 = null;
GLMModel model1 = null, model2 = null;
GLMParameters parms = new GLMParameters(Family.gaussian);
parms._train = _weighted._key;
parms._ignored_columns = new String[]{_weighted.name(0)};
parms._response_column = _weighted.name(1);
parms._standardize = true;
parms._objective_epsilon = 0;
parms._gradient_epsilon = 1e-10;
parms._max_iterations = 1000;
for (Solver s : GLMParameters.Solver.values()) {
// if(s != Solver.IRLSM)continue; //fixme: does not pass for other than IRLSM now
System.out.println("===============================================================");
System.out.println("Solver = " + s);
System.out.println("===============================================================");
try {
parms._lambda = null;
parms._alpha = null;
parms._train = _weighted._key;
parms._solver = s;
parms._weights_column = "weights";
job1 = new GLM(Key.make("prostate_model"), "glm test", parms);
model1 = job1.trainModel().get();
HashMap<String, Double> coefs1 = model1.coefficients();
System.out.println("coefs1 = " + coefs1);
parms._train = _upsampled._key;
parms._weights_column = null;
parms._lambda = null;
parms._alpha = null;
job2 = new GLM(Key.make("prostate_model"), "glm test", parms);
model2 = job2.trainModel().get();
HashMap<String, Double> coefs2 = model2.coefficients();
System.out.println("coefs2 = " + coefs2);
System.out.println("mse1 = " + model1._output._training_metrics.mse() + ", mse2 = " + model2._output._training_metrics.mse());
System.out.println( model1._output._training_metrics);
System.out.println( model2._output._training_metrics);
assertEquals(model2._output._training_metrics.mse(), model1._output._training_metrics.mse(),1e-6);
} finally {
if(job1 != null)job1.remove();
if(model1 != null) model1.delete();
if(job2 != null)job2.remove();
if(model2 != null) model2.delete();
}
}
}
@Test public void testTweedie() {
GLM job = null;
GLMModel model = null;
Frame scoreTrain = null;
// Call: glm(formula = Infections ~ ., family = tweedie(0), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// 0.8910 0.8221 0.7266 -0.5033 -0.2679 -0.1056
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 1564
// Residual Deviance: 1469 AIC: NA
// Call: glm(formula = Infections ~ ., family = tweedie(1), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// -0.12261 0.61149 0.53454 -0.37442 -0.18973 -0.08985
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 824.5
// Residual Deviance: 755.4 AIC: NA
// Call: glm(formula = Infections ~ ., family = tweedie(1.25), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// 1.02964 -0.14079 -0.12200 0.08502 0.04269 0.02105
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 834.2
// Residual Deviance: 770.8 AIC: NA
// Call: glm(formula = Infections ~ ., family = tweedie(1.5), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// 1.05665 -0.25891 -0.22185 0.15325 0.07624 0.03908
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 967
// Residual Deviance: 908.9 AIC: NA
// Call: glm(formula = Infections ~ ., family = tweedie(1.75), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// 1.08076 -0.35690 -0.30154 0.20556 0.10122 0.05375
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 1518
// Residual Deviance: 1465 AIC: NA
// Call: glm(formula = Infections ~ ., family = tweedie(2), data = D)
// Coefficients:
// (Intercept) SwimmerOccas LocationNonBeach Age20-24 Age25-29 SexMale
// 1.10230 -0.43751 -0.36337 0.24318 0.11830 0.06467
// Degrees of Freedom: 286 Total (i.e. Null); 281 Residual
// Null Deviance: 964.4
// Residual Deviance: 915.7 AIC: NA
String [] cfs1 = new String [] { "Intercept", "Swimmer.Occas", "Location.NonBeach", "Age.20-24", "Age.25-29", "Sex.Male" };
double [][] vals = new double[][] {{ 0.89100, 0.82210, 0.72660, -0.50330, -0.26790, -0.10560 },
{ -0.12261, 0.61149, 0.53454, -0.37442, -0.18973, -0.08985 },
{ 1.02964, -0.14079, -0.12200, 0.08502, 0.04269, 0.02105 },
{ 1.05665, -0.25891, -0.22185, 0.15325, 0.07624, 0.03908 },
{ 1.08076, -0.35690, -0.30154, 0.20556, 0.10122, 0.05375 },
{ 1.10230, -0.43751, -0.36337, 0.24318, 0.11830, 0.06467 },
};
int dof = 286, res_dof = 281;
double [] nullDev = new double[]{1564,824.5,834.2,967.0,1518,964.4};
double [] resDev = new double[]{1469,755.4,770.8,908.9,1465,915.7};
double [] varPow = new double[]{ 0, 1.0, 1.25, 1.5,1.75, 2.0};
GLMParameters parms = new GLMParameters(Family.tweedie);
parms._train = _earinf._key;
parms._ignored_columns = new String[]{};
// "response_column":"Claims","offset_column":"logInsured"
parms._response_column = "Infections";
parms._standardize = false;
parms._lambda = new double[]{0};
parms._alpha = new double[]{0};
parms._objective_epsilon = 0;
parms._gradient_epsilon = 1e-10;
parms._max_iterations = 1000;
for(int x = 0; x < varPow.length; ++x) {
double p = varPow[x];
parms._tweedie_variance_power = p;
parms._tweedie_link_power = 1 - p;
for (Solver s : /*new Solver[]{Solver.IRLSM}*/ GLMParameters.Solver.values()) {
try {
parms._solver = s;
job = new GLM(Key.make("prostate_model"), "glm test simple poisson", parms);
model = job.trainModel().get();
HashMap<String, Double> coefs = model.coefficients();
System.out.println("coefs = " + coefs);
for (int i = 0; i < cfs1.length; ++i)
assertEquals(vals[x][i], coefs.get(cfs1[i]), 1e-4);
assertEquals(nullDev[x], (GLMTest.nullDeviance(model)), 5e-4*nullDev[x]);
assertEquals(resDev[x], (GLMTest.residualDeviance(model)), 5e-4*resDev[x]);
assertEquals(dof, GLMTest.nullDOF(model), 0);
assertEquals(res_dof, GLMTest.resDOF(model), 0);
// test scoring
scoreTrain = model.score(_earinf);
hex.ModelMetricsRegressionGLM mmTrain = (ModelMetricsRegressionGLM) hex.ModelMetricsRegression.getFromDKV(model, _earinf);
assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8);
assertEquals(GLMTest.residualDeviance(model), mmTrain._resDev, 1e-8);
assertEquals(GLMTest.nullDeviance(model), mmTrain._nullDev, 1e-8);
} finally {
if (job != null) job.remove();
if (model != null) model.delete();
if (scoreTrain != null) scoreTrain.delete();
}
}
}
}
@Test
public void testPoissonWithOffset(){
GLM job = null;
GLMModel model = null;
Frame scoreTrain = null;
// Call: glm(formula = formula, family = poisson, data = D)
// Coefficients:
// (Intercept) Merit1 Merit2 Merit3 Class2 Class3 Class4 Class5
// -2.0357 -0.1378 -0.2207 -0.4930 0.2998 0.4691 0.5259 0.2156
// Degrees of Freedom: 19 Total (i.e. Null); 12 Residual
// Null Deviance: 33850
// Residual Deviance: 579.5 AIC: 805.9
String [] cfs1 = new String [] { "Intercept", "Merit.1", "Merit.2", "Merit.3", "Class.2", "Class.3", "Class.4", "Class.5"};
double [] vals = new double [] { -2.0357, -0.1378, -0.2207, -0.4930, 0.2998, 0.4691, 0.5259, 0.2156};
GLMParameters parms = new GLMParameters(Family.poisson);
parms._train = _canCarTrain._key;
parms._ignored_columns = new String[]{"Insured", "Premium", "Cost"};
// "response_column":"Claims","offset_column":"logInsured"
parms._response_column = "Claims";
parms._offset_column = "logInsured";
parms._standardize = false;
parms._lambda = new double[]{0};
parms._alpha = new double[]{0};
parms._objective_epsilon = 0;
parms._gradient_epsilon = 1e-10;
parms._max_iterations = 1000;
for (Solver s : GLMParameters.Solver.values()) {
try {
parms._solver = s;
job = new GLM(Key.make("prostate_model"), "glm test simple poisson", parms);
model = job.trainModel().get();
HashMap<String, Double> coefs = model.coefficients();
System.out.println("coefs = " + coefs);
for (int i = 0; i < cfs1.length; ++i)
assertEquals(vals[i], coefs.get(cfs1[i]), 1e-4);
assertEquals(33850, GLMTest.nullDeviance(model), 5);
assertEquals(579.5, GLMTest.residualDeviance(model), 1e-4*579.5);
assertEquals(19, GLMTest.nullDOF(model), 0);
assertEquals(12, GLMTest.resDOF(model), 0);
assertEquals(805.9, GLMTest.aic(model), 1e-4*805.9);
// test scoring
try {
Frame fr = new Frame(_canCarTrain.names(),_canCarTrain.vecs());
fr.remove(parms._offset_column);
scoreTrain = model.score(fr);
assertTrue("shoul've thrown IAE", false);
} catch (IllegalArgumentException iae) {
assertTrue(iae.getMessage().contains("Test/Validation dataset is missing offset vector"));
}
scoreTrain = model.score(_canCarTrain);
hex.ModelMetricsRegressionGLM mmTrain = (ModelMetricsRegressionGLM)hex.ModelMetricsRegression.getFromDKV(model, _canCarTrain);
assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8);
assertEquals(GLMTest.residualDeviance(model), mmTrain._resDev, 1e-8);
assertEquals(GLMTest.nullDeviance(model), mmTrain._nullDev, 1e-8);
} finally {
if(job != null)job.remove();
if(model != null) model.delete();
if(scoreTrain != null) scoreTrain.delete();
}
}
}
@Test
public void testPValuesTweedie() {
// Call:
// glm(formula = Infections ~ ., family = tweedie(var.power = 1.5),
// data = D)
// Deviance Residuals:
// Min 1Q Median 3Q Max
// -2.6355 -2.0931 -1.8183 0.5046 4.9458
// Coefficients:
// Estimate Std. Error t value Pr(>|t|)
// SwimmerOccas -0.25891 0.08455 -3.062 0.00241 **
// LocationNonBeach -0.22185 0.08393 -2.643 0.00867 **
// Age20-24 0.15325 0.10041 1.526 0.12808
// Age25-29 0.07624 0.10099 0.755 0.45096
// SexMale 0.03908 0.08619 0.453 0.65058
// (Dispersion parameter for Tweedie family taken to be 2.896306)
// Null deviance: 967.05 on 286 degrees of freedom
// Residual deviance: 908.86 on 281 degrees of freedom
// AIC: NA
// Number of Fisher Scoring iterations: 7
double [] sderr_exp = new double[]{ 0.11120211, 0.08454967, 0.08393315, 0.10041150, 0.10099231, 0.08618960};
double [] zvals_exp = new double[]{ 9.5021062, -3.0622693, -2.6431794, 1.5262357, 0.7548661, 0.4534433};
double [] pvals_exp = new double[]{ 9.508400e-19, 2.409514e-03, 8.674149e-03, 1.280759e-01, 4.509615e-01, 6.505795e-01 };
GLMParameters parms = new GLMParameters(Family.tweedie);
parms._tweedie_variance_power = 1.5;
parms._tweedie_link_power = 1 - parms._tweedie_variance_power;
parms._train = _earinf._key;
parms._standardize = false;
parms._lambda = new double[]{0};
parms._alpha = new double[]{0};
parms._response_column = "Infections";
parms._compute_p_values = true;
GLM job = new GLM(Key.make("prostate_model"), "glm test p-values", parms);
GLMModel model = null;
try {
model = job.trainModel().get();
String[] names_expected = new String[]{"Intercept", "Swimmer.Occas", "Location.NonBeach", "Age.20-24", "Age.25-29", "Sex.Male"};
String[] names_actual = model._output.coefficientNames();
HashMap<String, Integer> coefMap = new HashMap<>();
for (int i = 0; i < names_expected.length; ++i)
coefMap.put(names_expected[i], i);
double[] stder_actual = model._output.stdErr();
double[] zvals_actual = model._output.zValues();
double[] pvals_actual = model._output.pValues();
for (int i = 0; i < sderr_exp.length; ++i) {
int id = coefMap.get(names_actual[i]);
assertEquals(sderr_exp[id], stder_actual[i], sderr_exp[id] * 1e-3);
assertEquals(zvals_exp[id], zvals_actual[i], Math.abs(zvals_exp[id]) * 1e-3);
assertEquals(pvals_exp[id], pvals_actual[i], Math.max(1e-8,pvals_exp[id]) * 5e-3);
}
} finally {
if(model != null) model.delete();
if(job != null) job.remove();
}
}
@Test
public void testPValuesPoisson() {
// Coefficients:
// Estimate Std. Error z value Pr(>|z|)
// Class2 6.899e-02 8.006e-02 0.862 0.388785
// Class5 -4.468e-02 1.048e-01 -0.427 0.669732
// Insured 1.617e-06 5.069e-07 3.191 0.001420 **
// Cost 2.021e-05 6.869e-06 2.943 0.003252 **
// (Dispersion parameter for poisson family taken to be 1)
// Null deviance: 961181.685 on 19 degrees of freedom
// Residual deviance: 42.671 on 8 degrees of freedom
// AIC: 277.08
double [] sderr_exp = new double[]{ 3.480733e-01, 2.972063e-02, 3.858825e-02, 5.095260e-02,8.005579e-02, 6.332867e-02, 4.910690e-02, 1.047531e-01, 5.068602e-07, 1.086939e-05, 6.869142e-06 ,2.622370e-02};
double [] zvals_exp = new double[]{ -3.6734577, -5.0404946, -6.1269397, -6.2739848, 0.8618220, 4.5662083 , 5.5148904, -0.4265158 , 3.1906387, -3.3392867, 2.9428291, 35.8061272 };
double [] pvals_exp = new double[]{ 2.392903e-04, 4.643302e-07, 8.958540e-10 , 3.519228e-10, 3.887855e-01 , 4.966252e-06, 3.489974e-08 , 6.697321e-01 , 1.419587e-03, 8.399383e-04, 3.252279e-03, 8.867127e-281};
GLMParameters parms = new GLMParameters(Family.poisson);
parms._train = _canCarTrain._key;
parms._standardize = false;
parms._lambda = new double[]{0};
parms._alpha = new double[]{0};
parms._response_column = "Claims";
parms._compute_p_values = true;
GLM job = new GLM(Key.make("prostate_model"), "glm test p-values", parms);
GLMModel model = null;
try {
model = job.trainModel().get();
String[] names_expected = new String[]{"Intercept", "Merit.1", "Merit.2", "Merit.3", "Class.2", "Class.3", "Class.4", "Class.5","Insured","Premium", "Cost", "logInsured" };
String[] names_actual = model._output.coefficientNames();
HashMap<String, Integer> coefMap = new HashMap<>();
for (int i = 0; i < names_expected.length; ++i)
coefMap.put(names_expected[i], i);
double[] stder_actual = model._output.stdErr();
double[] zvals_actual = model._output.zValues();
double[] pvals_actual = model._output.pValues();
for (int i = 0; i < sderr_exp.length; ++i) {
int id = coefMap.get(names_actual[i]);
assertEquals(sderr_exp[id], stder_actual[i], sderr_exp[id] * 1e-4);
assertEquals(zvals_exp[id], zvals_actual[i], Math.abs(zvals_exp[id]) * 1e-4);
assertEquals(pvals_exp[id], pvals_actual[i], Math.max(1e-15,pvals_exp[id] * 1e-3));
}
} finally {
if(model != null) model.delete();
if(job != null) job.remove();
}
}
@Test
public void testPValuesGaussian(){
// 1) NON-STANDARDIZED
// summary(m)
// Call:
// glm(formula = CAPSULE ~ ., family = gaussian, data = D)
// Deviance Residuals:
// Min 1Q Median 3Q Max
// -0.8394 -0.3162 -0.1113 0.3771 0.9447
// Coefficients:
// Estimate Std. Error t value Pr(>|t|)
// (Intercept) -0.6870832 0.4035941 -1.702 0.08980 .
// ID 0.0003081 0.0002387 1.291 0.19791
// AGE -0.0006005 0.0040246 -0.149 0.88150
// RACER2 -0.0147733 0.2511007 -0.059 0.95313
// RACER3 -0.1456993 0.2593492 -0.562 0.57471
// DPROSb 0.1462512 0.0657117 2.226 0.02684 *
// DPROSc 0.2297207 0.0713659 3.219 0.00144 **
// DPROSd 0.1144974 0.0937208 1.222 0.22286
// DCAPSb 0.1430945 0.0888124 1.611 0.10827
// PSA 0.0047237 0.0015060 3.137 0.00189 **
// VOL -0.0019401 0.0013920 -1.394 0.16449
// (Dispersion parameter for gaussian family taken to be 0.1823264)
// Null deviance: 69.600 on 289 degrees of freedom
// Residual deviance: 50.687 on 278 degrees of freedom
// AIC: 343.16
// Number of Fisher Scoring iterations: 2
GLMParameters params = new GLMParameters(Family.gaussian);
params._response_column = "CAPSULE";
params._standardize = false;
params._train = _prostateTrain._key;
params._compute_p_values = true;
params._lambda = new double[]{0};
GLM job0 = null;
try {
job0 = new GLM(Key.make("prostate_model"), "glm test p-values", params);
params._solver = Solver.L_BFGS;
GLMModel model = job0.trainModel().get();
assertFalse("should've thrown, p-values only supported with IRLSM",true);
} catch(H2OModelBuilderIllegalArgumentException t) {
if(job0 != null)
job0.remove();
}
try {
job0 = new GLM(Key.make("prostate_model"), "glm test p-values", params);
params._solver = Solver.COORDINATE_DESCENT_NAIVE;
GLMModel model = job0.trainModel().get();
assertFalse("should've thrown, p-values only supported with IRLSM",true);
} catch(H2OModelBuilderIllegalArgumentException t) {
if(job0 != null)
job0.remove();
}
try {
job0 = new GLM(Key.make("prostate_model"), "glm test p-values", params);
params._solver = Solver.COORDINATE_DESCENT;
GLMModel model = job0.trainModel().get();
assertFalse("should've thrown, p-values only supported with IRLSM",true);
} catch(H2OModelBuilderIllegalArgumentException t) {
if(job0 != null)
job0.remove();
}
params._solver = Solver.IRLSM;
try {
job0 = new GLM(Key.make("prostate_model"), "glm test p-values", params);
params._lambda = new double[]{1};
GLMModel model = job0.trainModel().get();
assertFalse("should've thrown, p-values only supported with no regularization",true);
} catch(H2OModelBuilderIllegalArgumentException t) {
if(job0 != null)
job0.remove();
}
params._lambda = new double[]{0};
try {
params._lambda_search = true;
GLMModel model = job0.trainModel().get();
assertFalse("should've thrown, p-values only supported with no regularization (i.e. no lambda search)",true);
} catch(H2OModelBuilderIllegalArgumentException t) {
if(job0 != null)
job0.remove();
}
params._lambda_search = false;
GLM job = new GLM(Key.make("prostate_model"), "glm test p-values", params);
GLMModel model = null;
try {
model = job.trainModel().get();
String[] names_expected = new String[]{"Intercept", "ID", "AGE", "RACE.R2", "RACE.R3", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"};
double[] stder_expected = new double[]{0.4035941476, 0.0002387281, 0.0040245520, 0.2511007120, 0.2593492335, 0.0657117271, 0.0713659021, 0.0937207659, 0.0888124376, 0.0015060289, 0.0013919737, 0.0273258788};
double[] zvals_expected = new double[]{-1.70241133, 1.29061005, -0.14920829, -0.05883397, -0.56178799, 2.22564893, 3.21891333, 1.22168646, 1.61119882, 3.13650800, -1.39379859, 5.26524961 };
double[] pvals_expected = new double[]{8.979610e-02, 1.979113e-01, 8.814975e-01, 9.531266e-01, 5.747131e-01, 2.683977e-02, 1.439295e-03, 2.228612e-01, 1.082711e-01, 1.893210e-03, 1.644916e-01, 2.805776e-07};
String[] names_actual = model._output.coefficientNames();
HashMap<String, Integer> coefMap = new HashMap<>();
for (int i = 0; i < names_expected.length; ++i)
coefMap.put(names_expected[i], i);
double[] stder_actual = model._output.stdErr();
double[] zvals_actual = model._output.zValues();
double[] pvals_actual = model._output.pValues();
for (int i = 0; i < stder_expected.length; ++i) {
int id = coefMap.get(names_actual[i]);
assertEquals(stder_expected[id], stder_actual[i], stder_expected[id] * 1e-5);
assertEquals(zvals_expected[id], zvals_actual[i], Math.abs(zvals_expected[id]) * 1e-5);
assertEquals(pvals_expected[id], pvals_actual[i], pvals_expected[id] * 1e-3);
}
} finally {
if(model != null) model.delete();
if(job != null) job.remove();
}
// 2) STANDARDIZED
// Call:
// glm(formula = CAPSULE ~ ., family = binomial, data = Dstd)
// Deviance Residuals:
// Min 1Q Median 3Q Max
// -2.0601 -0.8079 -0.4491 0.8933 2.2877
// Coefficients:
// Estimate Std. Error z value Pr(>|z|)
// (Intercept) -1.28045 1.56879 -0.816 0.41438
// ID 0.19054 0.15341 1.242 0.21420
// AGE -0.02118 0.14498 -0.146 0.88384
// RACER2 0.06831 1.54240 0.044 0.96468
// RACER3 -0.74113 1.58272 -0.468 0.63959
// DPROSb 0.88833 0.39509 2.248 0.02455 *
// DPROSc 1.30594 0.41620 3.138 0.00170 **
// DPROSd 0.78440 0.54265 1.446 0.14832
// DCAPSb 0.61237 0.51796 1.182 0.23710
// PSA 0.60917 0.22447 2.714 0.00665 **
// VOL -0.18130 0.16204 -1.119 0.26320
// (Dispersion parameter for binomial family taken to be 1)
// Null deviance: 390.35 on 289 degrees of freedom
// Residual deviance: 297.65 on 278 degrees of freedom
// AIC: 321.65
// Number of Fisher Scoring iterations: 5
// Estimate Std. Error z value Pr(>|z|)
// (Intercept) -1.28045434 1.5687858 -0.81620723 4.143816e-01
// ID 0.19054396 0.1534062 1.24208800 2.142041e-01
// AGE -0.02118315 0.1449847 -0.14610616 8.838376e-01
// RACER2 0.06830776 1.5423974 0.04428674 9.646758e-01
// RACER3 -0.74113331 1.5827190 -0.46826589 6.395945e-01
// DPROSb 0.88832948 0.3950883 2.24843259 2.454862e-02
// DPROSc 1.30594011 0.4161974 3.13779030 1.702266e-03
// DPROSd 0.78440312 0.5426512 1.44550154 1.483171e-01
// DCAPSb 0.61237150 0.5179591 1.18227779 2.370955e-01
// PSA 0.60917093 0.2244733 2.71377864 6.652060e-03
// VOL -0.18129997 0.1620383 -1.11887108 2.631951e-01
// GLEASON 0.91750972 0.1963285 4.67333842 2.963429e-06
params._standardize = true;
job = new GLM(Key.make("prostate_model"), "glm test p-values", params);
try {
model = job.trainModel().get();
String[] names_expected = new String[]{"Intercept", "ID", "AGE", "RACE.R2", "RACE.R3", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"};
// do not compare std_err here, depends on the coefficients
// double[] stder_expected = new double[]{1.5687858, 0.1534062, 0.1449847, 1.5423974, 1.5827190, 0.3950883, 0.4161974, 0.5426512, 0.5179591, 0.2244733, 0.1620383, 0.1963285};
double[] zvals_expected = new double[]{1.14158283, 1.29061005, -0.14920829, -0.05883397, -0.56178799, 2.22564893, 3.21891333, 1.22168646, 1.61119882, 3.13650800, -1.39379859, 5.26524961 };
double[] pvals_expected = new double[]{2.546098e-01, 1.979113e-01, 8.814975e-01, 9.531266e-01, 5.747131e-01, 2.683977e-02, 1.439295e-03, 2.228612e-01, 1.082711e-01, 1.893210e-03, 1.644916e-01, 2.805776e-07 };
String[] names_actual = model._output.coefficientNames();
HashMap<String, Integer> coefMap = new HashMap<>();
for (int i = 0; i < names_expected.length; ++i)
coefMap.put(names_expected[i], i);
double[] zvals_actual = model._output.zValues();
double[] pvals_actual = model._output.pValues();
for (int i = 0; i < zvals_expected.length; ++i) {
int id = coefMap.get(names_actual[i]);
assertEquals(zvals_expected[id], zvals_actual[i], Math.abs(zvals_expected[id]) * 1e-5);
assertEquals(pvals_expected[id], pvals_actual[i], pvals_expected[id] * 1e-3);
}
} finally {
if(model != null) model.delete();
if(job != null) job.remove();
}
}
@AfterClass
public static void cleanUp() {
if(_canCarTrain != null)
_canCarTrain.delete();
if(_merit != null)
_merit.remove();
if(_class != null)
_class.remove();
if(_earinf != null)
_earinf.delete();
if(_weighted != null)
_weighted.delete();
if(_upsampled != null)
_upsampled.delete();
if(_prostateTrain != null)
_prostateTrain.delete();
}
} |
package com.Litterfeldt.AStory.models;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class FileSystem {
private static FileSystem mInstance = null;
public static FileSystem getInstance(){
if (mInstance == null) {
mInstance = new FileSystem();
}
return mInstance;
}
private File defaultDir;
private static MediaMetadataRetriever mmr;
private static final Set<String> acceptedFormats = new HashSet<String>(Arrays.asList(
new String[]{"mp3", "m4a", "aac", "flac"}
));
public FileSystem(){
defaultDir = new File(Environment.getExternalStorageDirectory() +"/Audiobooks");
if(!defaultDir.exists()){
defaultDir.mkdir();
defaultDir = new File(Environment.getExternalStorageDirectory() +"/Audiobooks");
}
mmr = new MediaMetadataRetriever();
}
public ArrayList<ArrayList<String>> allocateBookFolderContent(){
ArrayList<ArrayList<String>> bookPathList = new ArrayList<ArrayList<String>>();
File[] files = defaultDir.listFiles();
if (files == null){
return null;
}else {
for (File f : files){
if(f.isDirectory()){
ArrayList<String> dirList = new ArrayList<String>();
for (File d : f.listFiles()){
String fullPath = d.getAbsolutePath();
String fileType = fullPath.substring(fullPath.lastIndexOf(".")+1);
if(acceptedFormats.contains(fileType.toLowerCase())){
dirList.add(fullPath);
}
}
bookPathList.add(dirList);
}
else if (f.isFile()){
String fullpath = f.getAbsolutePath();
String filetype = fullpath.substring(fullpath.lastIndexOf(".")+1);
if(acceptedFormats.contains(filetype.toLowerCase())){
ArrayList<String> book = new ArrayList<String>();
book.add(fullpath);
bookPathList.add(book);
}}}
return bookPathList;
}
}
//Todo rewrite algorithm
public Book mockBookFromPath(ArrayList<String> paths){
if(paths.size() < 1) {
return null;
}
Collections.sort(paths);
String firstPath = paths.get(0);
mmr.setDataSource(firstPath);
String bookName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
if (bookName == null || bookName == ""){
bookName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
}
if (bookName == null || bookName == ""){
bookName = firstPath.substring(firstPath.lastIndexOf("/")+1,firstPath.lastIndexOf(".")).replaceAll("[^a-zA-Z ]", "").trim();
}
if (bookName == null || bookName == ""){
return null;
}
String author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
if (author == null || author == ""){
author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_WRITER);
}
if (author == null || author == ""){
author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR);
}
if (author == null || author == ""){
author = "Unknown Author";
}
byte[] img = mmr.getEmbeddedPicture();
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
for (String s : paths){
mmr.setDataSource(s);
String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
String chapterNum = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);
if(chapterNum == null) {
chapterNum = "" + paths.indexOf(s)+1;
}
Chapter c = new Chapter(0,s,toInteger(chapterNum), toInteger(duration));
chapters.add(c);
}
Book book = new Book(0,bookName,author,chapters,img);
return book;
}
private Integer toInteger(String str) {
String s = "";
for( char c : str.toCharArray()) {
if (!s.isEmpty() && !Character.isDigit(c)){ break; }
if (Character.isDigit(c)){ s+=c; }
}
return s.isEmpty() ? 0 : Integer.valueOf(s);
}
} |
package com.edinarobotics.zed.subsystems;
import com.edinarobotics.utils.commands.MaintainStateCommand;
import com.edinarobotics.utils.subsystems.Subsystem1816;
import edu.wpi.first.wpilibj.CANJaguar;
public class Shooter extends Subsystem1816 {
private static final int ENCODER_TICKS_PER_REV_1 = 180;
private static final int ENCODER_TICKS_PER_REV_2 = 180;
private final double P_SHOOTER_1 = 1;
private final double I_SHOOTER_1 = 0;
private final double D_SHOOTER_1 = 0;
private final double P_SHOOTER_2 = P_SHOOTER_1;
private final double I_SHOOTER_2 = I_SHOOTER_1;
private final double D_SHOOTER_2 = D_SHOOTER_1;
private double velocity;
private CANJaguar shooterJaguarFirst;
private CANJaguar shooterJaguarSecond;
public Shooter(int shooterJaguarPortNumber) {
try {
shooterJaguarFirst = new CANJaguar(shooterJaguarPortNumber);
shooterJaguarFirst.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder);
shooterJaguarFirst.configEncoderCodesPerRev(ENCODER_TICKS_PER_REV_1);
shooterJaguarFirst.changeControlMode(CANJaguar.ControlMode.kSpeed);
shooterJaguarFirst.setPID(P_SHOOTER_1, I_SHOOTER_1, D_SHOOTER_1);
}
catch(Exception e) {
System.err.println("Failed to create first shooter Jaguar.");
e.printStackTrace();
}
try {
shooterJaguarSecond = new CANJaguar(shooterJaguarPortNumber);
shooterJaguarSecond.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder);
shooterJaguarSecond.configEncoderCodesPerRev(ENCODER_TICKS_PER_REV_2);
shooterJaguarSecond.changeControlMode(CANJaguar.ControlMode.kSpeed);
shooterJaguarSecond.setPID(P_SHOOTER_2, I_SHOOTER_2, D_SHOOTER_2);
}
catch(Exception e) {
System.err.println("Failed to create second shooter Jaguar.");
e.printStackTrace();
}
}
protected void initDefaultCommand() {
setDefaultCommand(new MaintainStateCommand(this));
}
public void setShooterVelocity(double velocity) {
this.velocity = velocity;
update();
}
public void update() {
try {
if(shooterJaguarFirst != null) {
shooterJaguarFirst.setX(velocity);
}
if(shooterJaguarSecond != null) {
shooterJaguarSecond.setX(velocity);
}
}
catch(Exception e) {
System.err.println("Failed to update shooter Jaguar.");
e.printStackTrace();
}
}
} |
package com.fsck.k9.fragment;
import java.io.File;
import java.util.Collections;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.crypto.CryptoProvider.CryptoDecryptCallback;
import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
import com.fsck.k9.helper.FileBrowserHelper;
import com.fsck.k9.helper.FileBrowserHelper.FileBrowserFailOverCallback;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.view.AttachmentView;
import com.fsck.k9.view.AttachmentView.AttachmentFileDownloadCallback;
import com.fsck.k9.view.MessageHeader;
import com.fsck.k9.view.SingleMessageView;
public class MessageViewFragment extends SherlockFragment implements OnClickListener,
CryptoDecryptCallback, ConfirmationDialogFragmentListener {
private static final String ARG_REFERENCE = "reference";
private static final String STATE_MESSAGE_REFERENCE = "reference";
private static final String STATE_PGP_DATA = "pgpData";
private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
private static final int ACTIVITY_CHOOSE_DIRECTORY = 3;
public static MessageViewFragment newInstance(MessageReference reference) {
MessageViewFragment fragment = new MessageViewFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_REFERENCE, reference);
fragment.setArguments(args);
return fragment;
}
private SingleMessageView mMessageView;
private PgpData mPgpData;
private Account mAccount;
private MessageReference mMessageReference;
private Message mMessage;
private MessagingController mController;
private Listener mListener = new Listener();
private MessageViewHandler mHandler = new MessageViewHandler();
private LayoutInflater mLayoutInflater;
/** this variable is used to save the calling AttachmentView
* until the onActivityResult is called.
* => with this reference we can identity the caller
*/
private AttachmentView attachmentTmpStore;
/**
* Used to temporarily store the destination folder for refile operations if a confirmation
* dialog is shown.
*/
private String mDstFolder;
private MessageViewFragmentListener mFragmentListener;
/**
* {@code true} after {@link #onCreate(Bundle)} has been executed. This is used by
* {@code MessageList.configureMenu()} to make sure the fragment has been initialized before
* it is used.
*/
private boolean mInitialized = false;
class MessageViewHandler extends Handler {
public void progress(final boolean progress) {
post(new Runnable() {
@Override
public void run() {
setProgress(progress);
}
});
}
public void addAttachment(final View attachmentView) {
post(new Runnable() {
@Override
public void run() {
mMessageView.addAttachment(attachmentView);
}
});
}
/* A helper for a set of "show a toast" methods */
private void showToast(final String message, final int toastLength) {
post(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), message, toastLength).show();
}
});
}
public void networkError() {
// FIXME: This is a hack. Fix the Handler madness!
Context context = getActivity();
if (context == null) {
return;
}
showToast(context.getString(R.string.status_network_error), Toast.LENGTH_LONG);
}
public void invalidIdError() {
Context context = getActivity();
if (context == null) {
return;
}
showToast(context.getString(R.string.status_invalid_id_error), Toast.LENGTH_LONG);
}
public void fetchingAttachment() {
Context context = getActivity();
if (context == null) {
return;
}
showToast(context.getString(R.string.message_view_fetching_attachment_toast), Toast.LENGTH_SHORT);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mFragmentListener = (MessageViewFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.getClass() +
" must implement MessageViewFragmentListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This fragments adds options to the action bar
setHasOptionsMenu(true);
mController = MessagingController.getInstance(getActivity().getApplication());
mInitialized = true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = new ContextThemeWrapper(inflater.getContext(),
K9.getK9ThemeResourceId(K9.getK9MessageViewTheme()));
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mLayoutInflater.inflate(R.layout.message, container, false);
mMessageView = (SingleMessageView) view.findViewById(R.id.message_view);
//set a callback for the attachment view. With this callback the attachmentview
//request the start of a filebrowser activity.
mMessageView.setAttachmentCallback(new AttachmentFileDownloadCallback() {
@Override
public void showFileBrowser(final AttachmentView caller) {
FileBrowserHelper.getInstance()
.showFileBrowserActivity(MessageViewFragment.this,
null,
ACTIVITY_CHOOSE_DIRECTORY,
callback);
attachmentTmpStore = caller;
}
FileBrowserFailOverCallback callback = new FileBrowserFailOverCallback() {
@Override
public void onPathEntered(String path) {
attachmentTmpStore.writeFile(new File(path));
}
@Override
public void onCancel() {
// canceled, do nothing
}
};
});
mMessageView.initialize(this);
mMessageView.downloadRemainderButton().setOnClickListener(this);
mFragmentListener.messageHeaderViewAvailable(mMessageView.getMessageHeaderView());
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MessageReference messageReference;
if (savedInstanceState != null) {
mPgpData = (PgpData) savedInstanceState.get(STATE_PGP_DATA);
messageReference = (MessageReference) savedInstanceState.get(STATE_MESSAGE_REFERENCE);
} else {
Bundle args = getArguments();
messageReference = (MessageReference) args.getParcelable(ARG_REFERENCE);
}
displayMessage(messageReference, (mPgpData == null));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_MESSAGE_REFERENCE, mMessageReference);
outState.putSerializable(STATE_PGP_DATA, mPgpData);
}
public void displayMessage(MessageReference ref) {
displayMessage(ref, true);
}
private void displayMessage(MessageReference ref, boolean resetPgpData) {
mMessageReference = ref;
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "MessageView displaying message " + mMessageReference);
}
Context appContext = getActivity().getApplicationContext();
mAccount = Preferences.getPreferences(appContext).getAccount(mMessageReference.accountUuid);
if (resetPgpData) {
// start with fresh, empty PGP data
mPgpData = new PgpData();
}
// Clear previous message
mMessageView.resetView();
mMessageView.resetHeaderView();
mController.loadMessageForView(mAccount, mMessageReference.folderName, mMessageReference.uid, mListener);
mFragmentListener.updateMenu();
}
/**
* Called from UI thread when user select Delete
*/
public void onDelete() {
if (K9.confirmDelete() || (K9.confirmDeleteStarred() && mMessage.isSet(Flag.FLAGGED))) {
showDialog(R.id.dialog_confirm_delete);
} else {
delete();
}
}
public void onToggleAllHeadersView() {
mMessageView.getMessageHeaderView().onShowAdditionalHeaders();
}
public boolean allHeadersVisible() {
return mMessageView.getMessageHeaderView().additionalHeadersVisible();
}
private void delete() {
if (mMessage != null) {
// Disable the delete button after it's tapped (to try to prevent
// accidental clicks)
mFragmentListener.disableDeleteAction();
Message messageToDelete = mMessage;
mFragmentListener.showNextMessageOrReturn();
mController.deleteMessages(Collections.singletonList(messageToDelete), null);
}
}
public void onRefile(String dstFolder) {
if (!mController.isMoveCapable(mAccount)) {
return;
}
if (!mController.isMoveCapable(mMessage)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
if (K9.FOLDER_NONE.equalsIgnoreCase(dstFolder)) {
return;
}
if (mAccount.getSpamFolderName().equals(dstFolder) && K9.confirmSpam()) {
mDstFolder = dstFolder;
showDialog(R.id.dialog_confirm_spam);
} else {
refileMessage(dstFolder);
}
}
private void refileMessage(String dstFolder) {
String srcFolder = mMessageReference.folderName;
Message messageToMove = mMessage;
mFragmentListener.showNextMessageOrReturn();
mController.moveMessage(mAccount, srcFolder, messageToMove, dstFolder, null);
}
public void onReply() {
if (mMessage != null) {
mFragmentListener.onReply(mMessage, mPgpData);
}
}
public void onReplyAll() {
if (mMessage != null) {
mFragmentListener.onReplyAll(mMessage, mPgpData);
}
}
public void onForward() {
if (mMessage != null) {
mFragmentListener.onForward(mMessage, mPgpData);
}
}
public void onToggleFlagged() {
if (mMessage != null) {
boolean newState = !mMessage.isSet(Flag.FLAGGED);
mController.setFlag(mAccount, mMessage.getFolder().getName(),
new Message[] { mMessage }, Flag.FLAGGED, newState);
mMessageView.setHeaders(mMessage, mAccount);
}
}
public void onMove() {
if ((!mController.isMoveCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isMoveCapable(mMessage)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_MOVE);
}
public void onCopy() {
if ((!mController.isCopyCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isCopyCapable(mMessage)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_COPY);
}
public void onArchive() {
onRefile(mAccount.getArchiveFolderName());
}
public void onSpam() {
onRefile(mAccount.getSpamFolderName());
}
public void onSelectText() {
mMessageView.beginSelectingText();
}
private void startRefileActivity(int activity) {
Intent intent = new Intent(getActivity(), ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.folderName);
intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, mAccount.getLastSelectedFolderName());
intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference);
startActivityForResult(intent, activity);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mAccount.getCryptoProvider().onDecryptActivityResult(this, requestCode, resultCode, data, mPgpData)) {
return;
}
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case ACTIVITY_CHOOSE_DIRECTORY: {
if (resultCode == Activity.RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
attachmentTmpStore.writeFile(new File(filePath));
}
}
}
break;
}
case ACTIVITY_CHOOSE_FOLDER_MOVE:
case ACTIVITY_CHOOSE_FOLDER_COPY: {
if (data == null) {
return;
}
String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
MessageReference ref = data.getParcelableExtra(ChooseFolder.EXTRA_MESSAGE);
if (mMessageReference.equals(ref)) {
mAccount.setLastSelectedFolderName(destFolderName);
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE: {
mFragmentListener.showNextMessageOrReturn();
moveMessage(ref, destFolderName);
break;
}
case ACTIVITY_CHOOSE_FOLDER_COPY: {
copyMessage(ref, destFolderName);
break;
}
}
}
break;
}
}
}
public void onSendAlternate() {
if (mMessage != null) {
mController.sendAlternate(getActivity(), mAccount, mMessage);
}
}
public void onToggleRead() {
if (mMessage != null) {
mController.setFlag(mAccount, mMessage.getFolder().getName(),
new Message[] { mMessage }, Flag.SEEN, !mMessage.isSet(Flag.SEEN));
mMessageView.setHeaders(mMessage, mAccount);
String subject = mMessage.getSubject();
displayMessageSubject(subject);
mFragmentListener.updateMenu();
}
}
private void onDownloadRemainder() {
if (mMessage.isSet(Flag.X_DOWNLOADED_FULL)) {
return;
}
mMessageView.downloadRemainderButton().setEnabled(false);
mController.loadMessageForViewRemote(mAccount, mMessageReference.folderName, mMessageReference.uid, mListener);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.download: {
((AttachmentView)view).saveFile();
break;
}
case R.id.download_remainder: {
onDownloadRemainder();
break;
}
}
}
private void setProgress(boolean enable) {
if (mFragmentListener != null) {
mFragmentListener.setProgress(enable);
}
}
private void displayMessageSubject(String subject) {
if (mFragmentListener != null) {
mFragmentListener.displayMessageSubject(subject);
}
}
public void moveMessage(MessageReference reference, String destFolderName) {
mController.moveMessage(mAccount, mMessageReference.folderName, mMessage,
destFolderName, null);
}
public void copyMessage(MessageReference reference, String destFolderName) {
mController.copyMessage(mAccount, mMessageReference.folderName, mMessage,
destFolderName, null);
}
class Listener extends MessagingListener {
@Override
public void loadMessageForViewHeadersAvailable(final Account account, String folder, String uid,
final Message message) {
if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
|| !mMessageReference.accountUuid.equals(account.getUuid())) {
return;
}
final Message clonedMessage = message.clone();
mHandler.post(new Runnable() {
@Override
public void run() {
if (!clonedMessage.isSet(Flag.X_DOWNLOADED_FULL) &&
!clonedMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
String text = getString(R.string.message_view_downloading);
mMessageView.showStatusMessage(text);
}
mMessageView.setHeaders(clonedMessage, account);
final String subject = clonedMessage.getSubject();
if (subject == null || subject.equals("")) {
displayMessageSubject(getString(R.string.general_no_subject));
} else {
displayMessageSubject(clonedMessage.getSubject());
}
mMessageView.setOnFlagListener(new OnClickListener() {
@Override
public void onClick(View v) {
onToggleFlagged();
}
});
}
});
}
@Override
public void loadMessageForViewBodyAvailable(final Account account, String folder,
String uid, final Message message) {
if (!mMessageReference.uid.equals(uid) ||
!mMessageReference.folderName.equals(folder) ||
!mMessageReference.accountUuid.equals(account.getUuid())) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
try {
mMessage = message;
mMessageView.setMessage(account, (LocalMessage) message, mPgpData,
mController, mListener);
mFragmentListener.updateMenu();
} catch (MessagingException e) {
Log.v(K9.LOG_TAG, "loadMessageForViewBodyAvailable", e);
}
}
});
}
@Override
public void loadMessageForViewFailed(Account account, String folder, String uid, final Throwable t) {
if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
|| !mMessageReference.accountUuid.equals(account.getUuid())) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
setProgress(false);
if (t instanceof IllegalArgumentException) {
mHandler.invalidIdError();
} else {
mHandler.networkError();
}
if (mMessage == null || mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)) {
mMessageView.showStatusMessage(getString(R.string.webview_empty_message));
}
}
});
}
@Override
public void loadMessageForViewFinished(Account account, String folder, String uid, final Message message) {
if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
|| !mMessageReference.accountUuid.equals(account.getUuid())) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
setProgress(false);
mMessageView.setShowDownloadButton(message);
}
});
}
@Override
public void loadMessageForViewStarted(Account account, String folder, String uid) {
if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
|| !mMessageReference.accountUuid.equals(account.getUuid())) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
setProgress(true);
}
});
}
@Override
public void loadAttachmentStarted(Account account, Message message, Part part, Object tag, final boolean requiresDownload) {
if (mMessage != message) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
mMessageView.setAttachmentsEnabled(false);
showDialog(R.id.dialog_attachment_progress);
if (requiresDownload) {
mHandler.fetchingAttachment();
}
}
});
}
@Override
public void loadAttachmentFinished(Account account, Message message, Part part, final Object tag) {
if (mMessage != message) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
mMessageView.setAttachmentsEnabled(true);
removeDialog(R.id.dialog_attachment_progress);
Object[] params = (Object[]) tag;
boolean download = (Boolean) params[0];
AttachmentView attachment = (AttachmentView) params[1];
if (download) {
attachment.writeFile();
} else {
attachment.showFile();
}
}
});
}
@Override
public void loadAttachmentFailed(Account account, Message message, Part part, Object tag, String reason) {
if (mMessage != message) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
mMessageView.setAttachmentsEnabled(true);
removeDialog(R.id.dialog_attachment_progress);
mHandler.networkError();
}
});
}
}
// This REALLY should be in MessageCryptoView
@Override
public void onDecryptDone(PgpData pgpData) {
Account account = mAccount;
LocalMessage message = (LocalMessage) mMessage;
MessagingController controller = mController;
Listener listener = mListener;
try {
mMessageView.setMessage(account, message, pgpData, controller, listener);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "displayMessageBody failed", e);
}
}
private void showDialog(int dialogId) {
DialogFragment fragment;
switch (dialogId) {
case R.id.dialog_confirm_delete: {
String title = getString(R.string.dialog_confirm_delete_title);
String message = getString(R.string.dialog_confirm_delete_message);
String confirmText = getString(R.string.dialog_confirm_delete_confirm_button);
String cancelText = getString(R.string.dialog_confirm_delete_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
case R.id.dialog_confirm_spam: {
String title = getString(R.string.dialog_confirm_spam_title);
String message = getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, 1);
String confirmText = getString(R.string.dialog_confirm_spam_confirm_button);
String cancelText = getString(R.string.dialog_confirm_spam_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
case R.id.dialog_attachment_progress: {
String title = getString(R.string.dialog_attachment_progress_title);
fragment = ProgressDialogFragment.newInstance(title);
break;
}
default: {
throw new RuntimeException("Called showDialog(int) with unknown dialog id.");
}
}
fragment.setTargetFragment(this, dialogId);
fragment.show(getFragmentManager(), getDialogTag(dialogId));
}
private void removeDialog(int dialogId) {
FragmentManager fm = getFragmentManager();
// Make sure the "show dialog" transaction has been processed when we call
// findFragmentByTag() below. Otherwise the fragment won't be found and the dialog will
// never be dismissed.
fm.executePendingTransactions();
DialogFragment fragment = (DialogFragment) fm.findFragmentByTag(getDialogTag(dialogId));
if (fragment != null) {
fragment.dismiss();
}
}
private String getDialogTag(int dialogId) {
return String.format("dialog-%d", dialogId);
}
public void zoom(KeyEvent event) {
mMessageView.zoom(event);
}
@Override
public void doPositiveClick(int dialogId) {
switch (dialogId) {
case R.id.dialog_confirm_delete: {
delete();
break;
}
case R.id.dialog_confirm_spam: {
refileMessage(mDstFolder);
mDstFolder = null;
break;
}
}
}
@Override
public void doNegativeClick(int dialogId) {
/* do nothing */
}
@Override
public void dialogCancelled(int dialogId) {
/* do nothing */
}
/**
* Get the {@link MessageReference} of the currently displayed message.
*/
public MessageReference getMessageReference() {
return mMessageReference;
}
public boolean isMessageRead() {
return (mMessage != null) ? mMessage.isSet(Flag.SEEN) : false;
}
public boolean isCopyCapable() {
return mController.isCopyCapable(mAccount);
}
public boolean isMoveCapable() {
return mController.isMoveCapable(mAccount);
}
public boolean canMessageBeArchived() {
return (!mMessageReference.folderName.equals(mAccount.getArchiveFolderName())
&& mAccount.hasArchiveFolder());
}
public boolean canMessageBeMovedToSpam() {
return (!mMessageReference.folderName.equals(mAccount.getSpamFolderName())
&& mAccount.hasSpamFolder());
}
public void updateTitle() {
if (mMessage != null) {
displayMessageSubject(mMessage.getSubject());
}
}
public interface MessageViewFragmentListener {
public void onForward(Message mMessage, PgpData mPgpData);
public void disableDeleteAction();
public void onReplyAll(Message mMessage, PgpData mPgpData);
public void onReply(Message mMessage, PgpData mPgpData);
public void displayMessageSubject(String title);
public void setProgress(boolean b);
public void showNextMessageOrReturn();
public void messageHeaderViewAvailable(MessageHeader messageHeaderView);
public void updateMenu();
}
public boolean isInitialized() {
return mInitialized ;
}
public LayoutInflater getFragmentLayoutInflater() {
return mLayoutInflater;
}
} |
package com.fsck.k9.mail.transport;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.filter.Base64;
import com.fsck.k9.mail.filter.EOLConvertingOutputStream;
import com.fsck.k9.mail.filter.LineWrapOutputStream;
import com.fsck.k9.mail.filter.PeekableInputStream;
import com.fsck.k9.mail.filter.SmtpDataStuffing;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.store.TrustManagerFactory;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.*;
public class SmtpTransport extends Transport {
public static final String TRANSPORT_TYPE = "SMTP";
public static final int CONNECTION_SECURITY_NONE = 0;
public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1;
public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2;
public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3;
public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4;
public static final String AUTH_PLAIN = "PLAIN";
public static final String AUTH_CRAM_MD5 = "CRAM_MD5";
public static final String AUTH_LOGIN = "LOGIN";
public static final String AUTH_AUTOMATIC = "AUTOMATIC";
/**
* Decodes a SmtpTransport URI.
*
* <p>Possible forms:</p>
* <pre>
* smtp://user:password@server:port CONNECTION_SECURITY_NONE
* smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
* smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
* smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
* smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
* </pre>
*/
public static ServerSettings decodeUri(String uri) {
String host;
int port;
ConnectionSecurity connectionSecurity;
String authenticationType = null;
String username = null;
String password = null;
URI smtpUri;
try {
smtpUri = new URI(uri);
} catch (URISyntaxException use) {
throw new IllegalArgumentException("Invalid SmtpTransport URI", use);
}
String scheme = smtpUri.getScheme();
if (scheme.equals("smtp")) {
connectionSecurity = ConnectionSecurity.NONE;
port = 25;
} else if (scheme.equals("smtp+tls")) {
connectionSecurity = ConnectionSecurity.STARTTLS_OPTIONAL;
port = 25;
} else if (scheme.equals("smtp+tls+")) {
connectionSecurity = ConnectionSecurity.STARTTLS_REQUIRED;
port = 25;
} else if (scheme.equals("smtp+ssl+")) {
connectionSecurity = ConnectionSecurity.SSL_TLS_REQUIRED;
port = 465;
} else if (scheme.equals("smtp+ssl")) {
connectionSecurity = ConnectionSecurity.SSL_TLS_OPTIONAL;
port = 465;
} else {
throw new IllegalArgumentException("Unsupported protocol (" + scheme + ")");
}
host = smtpUri.getHost();
if (smtpUri.getPort() != -1) {
port = smtpUri.getPort();
}
if (smtpUri.getUserInfo() != null) {
try {
String[] userInfoParts = smtpUri.getUserInfo().split(":");
username = URLDecoder.decode(userInfoParts[0], "UTF-8");
if (userInfoParts.length > 1) {
password = URLDecoder.decode(userInfoParts[1], "UTF-8");
}
if (userInfoParts.length > 2) {
authenticationType = userInfoParts[2];
}
} catch (UnsupportedEncodingException enc) {
// This shouldn't happen since the encoding is hardcoded to UTF-8
throw new IllegalArgumentException("Couldn't urldecode username or password.", enc);
}
}
return new ServerSettings(TRANSPORT_TYPE, host, port, connectionSecurity,
authenticationType, username, password);
}
/**
* Creates a SmtpTransport URI with the supplied settings.
*
* @param server
* The {@link ServerSettings} object that holds the server settings.
*
* @return A SmtpTransport URI that holds the same information as the {@code server} parameter.
*
* @see Account#getTransportUri()
* @see SmtpTransport#decodeUri(String)
*/
public static String createUri(ServerSettings server) {
String userEnc;
String passwordEnc;
try {
userEnc = (server.username != null) ?
URLEncoder.encode(server.username, "UTF-8") : "";
passwordEnc = (server.password != null) ?
URLEncoder.encode(server.password, "UTF-8") : "";
}
catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Could not encode username or password", e);
}
String scheme;
switch (server.connectionSecurity) {
case SSL_TLS_OPTIONAL:
scheme = "smtp+ssl";
break;
case SSL_TLS_REQUIRED:
scheme = "smtp+ssl+";
break;
case STARTTLS_OPTIONAL:
scheme = "smtp+tls";
break;
case STARTTLS_REQUIRED:
scheme = "smtp+tls+";
break;
default:
case NONE:
scheme = "smtp";
break;
}
String authType = server.authenticationType;
if (!(AUTH_AUTOMATIC.equals(authType) ||
AUTH_LOGIN.equals(authType) ||
AUTH_PLAIN.equals(authType) ||
AUTH_CRAM_MD5.equals(authType))) {
throw new IllegalArgumentException("Invalid authentication type: " + authType);
}
String userInfo = userEnc + ":" + passwordEnc + ":" + authType;
try {
return new URI(scheme, userInfo, server.host, server.port, null, null,
null).toString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Can't create SmtpTransport URI", e);
}
}
String mHost;
int mPort;
String mUsername;
String mPassword;
String mAuthType;
int mConnectionSecurity;
boolean mSecure;
Socket mSocket;
PeekableInputStream mIn;
OutputStream mOut;
private boolean m8bitEncodingAllowed;
private int mLargestAcceptableMessage;
public SmtpTransport(String uri) throws MessagingException {
ServerSettings settings;
try {
settings = decodeUri(uri);
} catch (IllegalArgumentException e) {
throw new MessagingException("Error while decoding transport URI", e);
}
mHost = settings.host;
mPort = settings.port;
switch (settings.connectionSecurity) {
case NONE:
mConnectionSecurity = CONNECTION_SECURITY_NONE;
break;
case STARTTLS_OPTIONAL:
mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL;
break;
case STARTTLS_REQUIRED:
mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED;
break;
case SSL_TLS_OPTIONAL:
mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL;
break;
case SSL_TLS_REQUIRED:
mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED;
break;
}
mAuthType = settings.authenticationType;
mUsername = settings.username;
mPassword = settings.password;
}
@Override
public void open() throws MessagingException {
try {
InetAddress[] addresses = InetAddress.getAllByName(mHost);
for (int i = 0; i < addresses.length; i++) {
try {
SocketAddress socketAddress = new InetSocketAddress(addresses[i], mPort);
if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED ||
mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) {
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
mSecure = true;
} else {
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
} catch (ConnectException e) {
if (i < (addresses.length - 1)) {
// there are still other addresses for that host to try
continue;
}
throw new MessagingException("Cannot connect to host", e);
}
break; // connection success
}
// RFC 1047
mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024));
mOut = mSocket.getOutputStream();
// Eat the banner
executeSimpleCommand(null);
InetAddress localAddress = mSocket.getLocalAddress();
String localHost = localAddress.getCanonicalHostName();
String ipAddr = localAddress.getHostAddress();
if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) {
// We don't have a FQDN or the hostname contains invalid
// characters (see issue 2143), so use IP address.
if (!ipAddr.equals("")) {
if (localAddress instanceof Inet6Address) {
localHost = "[IPV6:" + ipAddr + "]";
} else {
localHost = "[" + ipAddr + "]";
}
} else {
// If the IP address is no good, set a sane default (see issue 2750).
localHost = "android";
}
}
List<String> results = executeSimpleCommand("EHLO " + localHost);
m8bitEncodingAllowed = results.contains("8BITMIME");
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL
|| mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
if (results.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort,
true);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(),
1024));
mOut = mSocket.getOutputStream();
mSecure = true;
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
results = executeSimpleCommand("EHLO " + localHost);
} else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
throw new MessagingException("TLS not supported but required");
}
}
boolean useAuthLogin = AUTH_LOGIN.equals(mAuthType);
boolean useAuthPlain = AUTH_PLAIN.equals(mAuthType);
boolean useAuthCramMD5 = AUTH_CRAM_MD5.equals(mAuthType);
// Automatically choose best authentication method if none was explicitly selected
boolean useAutomaticAuth = !(useAuthLogin || useAuthPlain || useAuthCramMD5);
boolean authLoginSupported = false;
boolean authPlainSupported = false;
boolean authCramMD5Supported = false;
for (String result : results) {
if (result.matches(".*AUTH.*LOGIN.*$")) {
authLoginSupported = true;
}
if (result.matches(".*AUTH.*PLAIN.*$")) {
authPlainSupported = true;
}
if (result.matches(".*AUTH.*CRAM-MD5.*$")) {
authCramMD5Supported = true;
}
if (result.matches(".*SIZE \\d*$")) {
try {
mLargestAcceptableMessage = Integer.parseInt(result.substring(result.lastIndexOf(' ') + 1));
} catch (Exception e) {
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Tried to parse " + result + " and get an int out of the last word: " + e);
}
}
}
}
if (mUsername != null && mUsername.length() > 0 &&
mPassword != null && mPassword.length() > 0) {
if (useAuthCramMD5 || (useAutomaticAuth && authCramMD5Supported)) {
if (!authCramMD5Supported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using CRAM_MD5 as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
saslAuthCramMD5(mUsername, mPassword);
} else if (useAuthPlain || (useAutomaticAuth && authPlainSupported)) {
if (!authPlainSupported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using PLAIN as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
try {
saslAuthPlain(mUsername, mPassword);
} catch (MessagingException ex) {
// PLAIN is a special case. Historically, PLAIN has represented both PLAIN and LOGIN; only the
// protocol being advertised by the server would be used, with PLAIN taking precedence. Instead
// of using only the requested protocol, we'll try PLAIN and then try LOGIN.
if (useAuthPlain && authLoginSupported) {
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using legacy PLAIN authentication behavior and trying LOGIN.");
}
saslAuthLogin(mUsername, mPassword);
} else {
// If it was auto detected and failed, continue throwing the exception back up.
throw ex;
}
}
} else if (useAuthLogin || (useAutomaticAuth && authLoginSupported)) {
if (!authPlainSupported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using LOGIN as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
saslAuthLogin(mUsername, mPassword);
} else {
throw new MessagingException("No valid authentication mechanism found.");
}
}
} catch (SSLException e) {
throw new CertificateValidationException(e.getMessage(), e);
} catch (GeneralSecurityException gse) {
throw new MessagingException(
"Unable to open connection to SMTP server due to security error.", gse);
} catch (IOException ioe) {
throw new MessagingException("Unable to open connection to SMTP server.", ioe);
}
}
@Override
public void sendMessage(Message message) throws MessagingException {
ArrayList<Address> addresses = new ArrayList<Address>();
{
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO)));
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.CC)));
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.BCC)));
}
message.setRecipients(RecipientType.BCC, null);
HashMap<String, ArrayList<String>> charsetAddressesMap =
new HashMap<String, ArrayList<String>>();
for (Address address : addresses) {
String addressString = address.getAddress();
String charset = MimeUtility.getCharsetFromAddress(addressString);
ArrayList<String> addressesOfCharset = charsetAddressesMap.get(charset);
if (addressesOfCharset == null) {
addressesOfCharset = new ArrayList<String>();
charsetAddressesMap.put(charset, addressesOfCharset);
}
addressesOfCharset.add(addressString);
}
for (Map.Entry<String, ArrayList<String>> charsetAddressesMapEntry :
charsetAddressesMap.entrySet()) {
String charset = charsetAddressesMapEntry.getKey();
ArrayList<String> addressesOfCharset = charsetAddressesMapEntry.getValue();
message.setCharset(charset);
sendMessageTo(addressesOfCharset, message);
}
}
private void sendMessageTo(ArrayList<String> addresses, Message message)
throws MessagingException {
boolean possibleSend = false;
close();
open();
message.setEncoding(m8bitEncodingAllowed ? "8bit" : null);
// If the message has attachments and our server has told us about a limit on
// the size of messages, count the message's size before sending it
if (mLargestAcceptableMessage > 0 && ((LocalMessage)message).hasAttachments()) {
if (message.calculateSize() > mLargestAcceptableMessage) {
MessagingException me = new MessagingException("Message too large for server");
me.setPermanentFailure(possibleSend);
throw me;
}
}
Address[] from = message.getFrom();
try {
//TODO: Add BODY=8BITMIME parameter if appropriate?
executeSimpleCommand("MAIL FROM:" + "<" + from[0].getAddress() + ">");
for (String address : addresses) {
executeSimpleCommand("RCPT TO:" + "<" + address + ">");
}
executeSimpleCommand("DATA");
EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream(
new SmtpDataStuffing(
new LineWrapOutputStream(
new BufferedOutputStream(mOut, 1024),
1000)));
message.writeTo(msgOut);
// We use BufferedOutputStream. So make sure to call flush() !
msgOut.flush();
possibleSend = true; // After the "\r\n." is attempted, we may have sent the message
executeSimpleCommand("\r\n.");
} catch (Exception e) {
MessagingException me = new MessagingException("Unable to send message", e);
// "5xx text" -responses are permanent failures
String msg = e.getMessage();
if (msg != null && msg.startsWith("5")) {
Log.w(K9.LOG_TAG, "handling 5xx SMTP error code as a permanent failure");
possibleSend = false;
}
me.setPermanentFailure(possibleSend);
throw me;
} finally {
close();
}
}
@Override
public void close() {
try {
executeSimpleCommand("QUIT");
} catch (Exception e) {
}
try {
mIn.close();
} catch (Exception e) {
}
try {
mOut.close();
} catch (Exception e) {
}
try {
mSocket.close();
} catch (Exception e) {
}
mIn = null;
mOut = null;
mSocket = null;
}
private String readLine() throws IOException {
StringBuilder sb = new StringBuilder();
int d;
while ((d = mIn.read()) != -1) {
if (((char)d) == '\r') {
continue;
} else if (((char)d) == '\n') {
break;
} else {
sb.append((char)d);
}
}
String ret = sb.toString();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP)
Log.d(K9.LOG_TAG, "SMTP <<< " + ret);
return ret;
}
private void writeLine(String s, boolean sensitive) throws IOException {
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
final String commandToLog;
if (sensitive && !K9.DEBUG_SENSITIVE) {
commandToLog = "SMTP >>> *sensitive*";
} else {
commandToLog = "SMTP >>> " + s;
}
Log.d(K9.LOG_TAG, commandToLog);
}
byte[] data = s.concat("\r\n").getBytes();
/*
* Important: Send command + CRLF using just one write() call. Using
* multiple calls will likely result in multiple TCP packets and some
* SMTP servers misbehave if CR and LF arrive in separate pakets.
* See issue 799.
*/
mOut.write(data);
mOut.flush();
}
private void checkLine(String line) throws MessagingException {
if (line.length() < 1) {
throw new MessagingException("SMTP response is 0 length");
}
char c = line.charAt(0);
if ((c == '4') || (c == '5')) {
throw new MessagingException(line);
}
}
private List<String> executeSimpleCommand(String command) throws IOException, MessagingException {
return executeSimpleCommand(command, false);
}
private List<String> executeSimpleCommand(String command, boolean sensitive)
throws IOException, MessagingException {
List<String> results = new ArrayList<String>();
if (command != null) {
writeLine(command, sensitive);
}
/*
* Read lines as long as the length is 4 or larger, e.g. "220-banner text here".
* Shorter lines are either errors of contain only a reply code. Those cases will
* be handled by checkLine() below.
*/
String line = readLine();
while (line.length() >= 4) {
if (line.length() > 4) {
// Everything after the first four characters goes into the results array.
results.add(line.substring(4));
}
if (line.charAt(3) != '-') {
// If the fourth character isn't "-" this is the last line of the response.
break;
}
line = readLine();
}
// Check if the reply code indicates an error.
checkLine(line);
return results;
}
// C: AUTH LOGIN
// S: 334 VXNlcm5hbWU6
// C: d2VsZG9u
// S: 334 UGFzc3dvcmQ6
// C: dzNsZDBu
// S: 235 2.0.0 OK Authenticated
// Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads:
// C: AUTH LOGIN
// S: 334 Username:
// C: weldon
// S: 334 Password:
// C: w3ld0n
// S: 235 2.0.0 OK Authenticated
private void saslAuthLogin(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
try {
executeSimpleCommand("AUTH LOGIN");
executeSimpleCommand(new String(Base64.encodeBase64(username.getBytes())), true);
executeSimpleCommand(new String(Base64.encodeBase64(password.getBytes())), true);
} catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException("AUTH LOGIN failed (" + me.getMessage()
+ ")");
}
throw me;
}
}
private void saslAuthPlain(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
byte[] data = ("\000" + username + "\000" + password).getBytes();
data = new Base64().encode(data);
try {
executeSimpleCommand("AUTH PLAIN " + new String(data), true);
} catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException("AUTH PLAIN failed (" + me.getMessage()
+ ")");
}
throw me;
}
}
private void saslAuthCramMD5(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
List<String> respList = executeSimpleCommand("AUTH CRAM-MD5");
if (respList.size() != 1) {
throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5");
}
String b64Nonce = respList.get(0);
String b64CRAMString = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce);
try {
executeSimpleCommand(b64CRAMString, true);
} catch (MessagingException me) {
throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM");
}
}
} |
package com.hp.hpl.jena.assembler;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.*;
/**
The ModelExpansion code expands a model <code>M</code> against a
schema <code>S</code>, returning a new model which contains
<ul>
<li>the statements of M
<li>any statements (A rdfs:subClassOf B) from S where neither A nor B
is a bnode.
<li>statements (A rdf:type T) if M contains (A P any) and
S contains (P rdfs:domain T).
<li>statements (A rdf:type T) if M contains (any P A) and
S contains (P rdfs:range T).
<li>statements (A rdf:type T) if (A rdf:type U) and (U rdfs:subClassOf T).
</ul>
This is sufficient to allow the subjects in <code>M</code> which have
properties from <code>S</code> to have enough type information for
AssemblerGroup dispatch.
@author kers
*/
public class ModelExpansion
{
public static Model withSchema( Model model, Model schema )
{
Model result = ModelFactory.createDefaultModel().add( model );
addSubclassesFrom( result, schema );
addDomainTypes( result, schema );
addRangeTypes( result, schema );
addSupertypes( result );
return result;
}
private static final Property ANY = null;
protected static void addSubclassesFrom( Model result, Model schema )
{
for (StmtIterator it = schema.listStatements( ANY, RDFS.subClassOf, ANY ); it.hasNext();)
{
Statement s = it.nextStatement();
if (s.getSubject().isURIResource() && s.getObject().isURIResource()) result.add( s );
}
}
protected static void addDomainTypes( Model result, Model schema )
{
for (StmtIterator it = schema.listStatements( ANY, RDFS.domain, ANY ); it.hasNext();)
{
Statement s = it.nextStatement();
Property property = (Property) s.getSubject().as( Property.class );
RDFNode type = s.getObject();
for (StmtIterator x = result.listStatements( ANY, property, ANY ); x.hasNext();)
{
Statement t = x.nextStatement();
result.add( t.getSubject(), RDF.type, type );
}
}
}
protected static void addRangeTypes( Model result, Model schema )
{
for (StmtIterator it = schema.listStatements( ANY, RDFS.range, ANY ); it.hasNext();)
{
Statement s = it.nextStatement();
RDFNode type = s.getObject();
Property property = (Property) s.getSubject().as( Property.class );
for (StmtIterator x = result.listStatements( ANY, property, ANY ); x.hasNext();)
{
RDFNode ob = x.nextStatement().getObject();
if (ob.isResource()) result.add( (Resource) ob, RDF.type, type );
}
}
}
protected static Resource getResource( Statement s )
{
RDFNode ob = s.getObject();
if (ob.isLiteral()) throw new BadObjectException( s );
return (Resource) ob;
}
protected static void addSupertypes( Model result )
{
Model temp = ModelFactory.createDefaultModel();
for (StmtIterator it = result.listStatements( ANY, RDF.type, ANY ); it.hasNext();)
{
Statement s = it.nextStatement();
Resource c = getResource( s );
for (StmtIterator subclasses = result.listStatements( c, RDFS.subClassOf, ANY ); subclasses.hasNext();)
{
RDFNode type = subclasses.nextStatement().getObject();
// System.err.println( ">> adding super type: subject " + s.getSubject() + ", type " + type );
temp.add( s.getSubject(), RDF.type, type );
}
}
result.add( temp );
}
} |
package com.humbughq.android;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
class HumbugAsyncPushTask extends AsyncTask<String, String, String> {
HumbugActivity context;
List<NameValuePair> nameValuePairs;
AsyncTaskCompleteListener callback;
interface AsyncTaskCompleteListener {
public void onTaskComplete(String result);
}
public HumbugAsyncPushTask(HumbugActivity humbugActivity) {
context = humbugActivity;
callback = new AsyncTaskCompleteListener() {
@Override
public void onTaskComplete(String result) {
// Dummy method which does nothing
}
};
nameValuePairs = new ArrayList<NameValuePair>();
}
public void setCallback(AsyncTaskCompleteListener listener) {
callback = listener;
}
public void setProperty(String key, String value) {
this.nameValuePairs.add(new BasicNameValuePair(key, value));
}
protected String doInBackground(String... api_path) {
AndroidHttpClient httpclient = AndroidHttpClient
.newInstance(HumbugActivity.USER_AGENT);
HttpResponse response;
String responseString = null;
try {
HttpPost httppost = new HttpPost(HumbugActivity.SERVER_URI
+ api_path[0]);
Log.i("welp", HumbugActivity.SERVER_URI + api_path[0]);
nameValuePairs.add(new BasicNameValuePair("api-key",
this.context.api_key));
nameValuePairs.add(new BasicNameValuePair("email",
this.context.email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// timeout after 55 seconds in ms
HttpConnectionParams.setSoTimeout(httppost.getParams(), 55 * 1000);
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpclient.close();
Log.i("HAPT", "F" + responseString);
return responseString;
}
} |
package com.irccloud.android;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
public class BuffersListFragment extends SherlockListFragment {
private static final int TYPE_SERVER = 0;
private static final int TYPE_CHANNEL = 1;
private static final int TYPE_CONVERSATION = 2;
private static final int TYPE_ARCHIVES_HEADER = 3;
NetworkConnection conn;
BufferListAdapter adapter;
OnBufferSelectedListener mListener;
View view;
TextView errorMsg;
RelativeLayout connecting = null;
LinearLayout topUnreadIndicator = null;
LinearLayout topUnreadIndicatorColor = null;
LinearLayout bottomUnreadIndicator = null;
LinearLayout bottomUnreadIndicatorColor = null;
String error = null;
private Timer countdownTimer = null;
int firstUnreadPosition = -1;
int lastUnreadPosition= -1;
int firstHighlightPosition = -1;
int lastHighlightPosition= -1;
SparseBooleanArray mExpandArchives = new SparseBooleanArray();
private static class BufferListEntry implements Serializable {
private static final long serialVersionUID = 1848168221883194027L;
int cid;
int bid;
int type;
int unread;
int highlights;
int key;
long last_seen_eid;
long min_eid;
int joined;
int archived;
String name;
String status;
}
private class BufferListAdapter extends BaseAdapter {
ArrayList<BufferListEntry> data;
private SherlockListFragment ctx;
private class ViewHolder {
int type;
TextView label;
TextView highlights;
LinearLayout unread;
LinearLayout groupbg;
LinearLayout bufferbg;
ImageView key;
ProgressBar progress;
ImageButton addBtn;
}
public BufferListAdapter(SherlockListFragment context) {
ctx = context;
data = new ArrayList<BufferListEntry>();
}
public void setItems(ArrayList<BufferListEntry> items) {
data = items;
}
int unreadPositionAbove(int pos) {
for(int i = pos-1; i >= 0; i
BufferListEntry e = data.get(i);
if(e.unread > 0)
return i;
}
return 0;
}
int unreadPositionBelow(int pos) {
for(int i = pos; i < data.size(); i++) {
BufferListEntry e = data.get(i);
if(e.unread > 0)
return i;
}
return data.size() - 1;
}
public BufferListEntry buildItem(int cid, int bid, int type, String name, int key, int unread, int highlights, long last_seen_eid, long min_eid, int joined, int archived, String status) {
BufferListEntry e = new BufferListEntry();
e.cid = cid;
e.bid = bid;
e.type = type;
e.name = name;
e.key = key;
e.unread = unread;
e.highlights = highlights;
e.last_seen_eid = last_seen_eid;
e.min_eid = min_eid;
e.joined = joined;
e.archived = archived;
e.status = status;
return e;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
BufferListEntry e = data.get(position);
return e.bid;
}
@SuppressWarnings("deprecation")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
BufferListEntry e = data.get(position);
View row = convertView;
ViewHolder holder;
if(row != null && ((ViewHolder)row.getTag()).type != e.type)
row = null;
if (row == null) {
LayoutInflater inflater = ctx.getLayoutInflater(null);
if(e.type == TYPE_SERVER)
row = inflater.inflate(R.layout.row_buffergroup, null);
else
row = inflater.inflate(R.layout.row_buffer, null);
holder = new ViewHolder();
holder.label = (TextView) row.findViewById(R.id.label);
holder.highlights = (TextView) row.findViewById(R.id.highlights);
holder.unread = (LinearLayout) row.findViewById(R.id.unread);
holder.groupbg = (LinearLayout) row.findViewById(R.id.groupbg);
holder.bufferbg = (LinearLayout) row.findViewById(R.id.bufferbg);
holder.key = (ImageView) row.findViewById(R.id.key);
holder.progress = (ProgressBar) row.findViewById(R.id.progressBar);
holder.addBtn = (ImageButton) row.findViewById(R.id.addBtn);
holder.type = e.type;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.label.setText(e.name);
if(e.type == TYPE_ARCHIVES_HEADER) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archives_heading));
holder.unread.setBackgroundDrawable(null);
if(mExpandArchives.get(e.cid, false)) {
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived);
holder.bufferbg.setSelected(true);
} else {
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg);
holder.bufferbg.setSelected(false);
}
} else if(e.archived == 1 && holder.bufferbg != null) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_archived));
holder.bufferbg.setBackgroundResource(R.drawable.row_buffer_bg_archived);
holder.unread.setBackgroundDrawable(null);
} else if((e.type == TYPE_CHANNEL && e.joined == 0) || !e.status.equals("connected_ready")) {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_inactive));
holder.unread.setBackgroundDrawable(null);
} else if(e.unread > 0) {
holder.label.setTypeface(null, Typeface.BOLD);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label_unread));
holder.unread.setBackgroundResource(R.drawable.selected_blue);
} else {
holder.label.setTypeface(null);
holder.label.setTextColor(getResources().getColorStateList(R.color.row_label));
holder.unread.setBackgroundDrawable(null);
}
if(conn.getState() != NetworkConnection.STATE_CONNECTED)
row.setBackgroundResource(R.drawable.disconnected_yellow);
else
row.setBackgroundResource(R.drawable.bg);
if(holder.key != null) {
if(e.key > 0) {
holder.key.setVisibility(View.VISIBLE);
} else {
holder.key.setVisibility(View.INVISIBLE);
}
}
if(holder.progress != null) {
if(e.status.equals("connected_ready") || e.status.equals("quitting") || e.status.equals("disconnected")) {
holder.progress.setVisibility(View.GONE);
} else {
holder.progress.setVisibility(View.VISIBLE);
}
}
if(holder.groupbg != null) {
if(e.status.equals("waiting_to_retry") || e.status.equals("pool_unavailable")) {
holder.groupbg.setBackgroundResource(R.drawable.operator_bg_red);
holder.label.setTextColor(getResources().getColorStateList(R.color.heading_operators));
} else {
holder.groupbg.setBackgroundResource(R.drawable.row_buffergroup_bg);
}
}
if(holder.highlights != null) {
if(e.highlights > 0) {
holder.highlights.setVisibility(View.VISIBLE);
holder.highlights.setText("(" + e.highlights + ")");
} else {
holder.highlights.setVisibility(View.GONE);
holder.highlights.setText("");
}
}
if(holder.addBtn != null) {
holder.addBtn.setTag(e);
holder.addBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final BufferListEntry e = (BufferListEntry)v.getTag();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_textprompt,null);
TextView prompt = (TextView)view.findViewById(R.id.prompt);
final EditText input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Which channel would you like to join?");
builder.setTitle(e.name);
builder.setView(view);
builder.setPositiveButton("Join", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] splitchannels = input.getText().toString().split(",");
for(int i = 0; i < splitchannels.length; i++) {
String[] channelandkey = splitchannels[i].split(" ");
if(channelandkey.length > 1)
NetworkConnection.getInstance().join(e.cid, channelandkey[0].trim(), channelandkey[1]);
else
NetworkConnection.getInstance().join(e.cid, channelandkey[0].trim(), "");
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(getActivity());
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
});
}
return row;
}
}
private class RefreshTask extends AsyncTask<Void, Void, Void> {
ArrayList<BufferListEntry> entries = new ArrayList<BufferListEntry>();
@Override
protected Void doInBackground(Void... params) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
if(adapter == null) {
adapter = new BufferListAdapter(BuffersListFragment.this);
}
firstUnreadPosition = -1;
lastUnreadPosition = -1;
firstHighlightPosition = -1;
lastHighlightPosition = -1;
int position = 0;
for(int i = 0; i < servers.size(); i++) {
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.type.equalsIgnoreCase("console")) {
int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid);
if(s.name.length() == 0)
s.name = s.hostname;
entries.add(adapter.buildItem(b.cid, b.bid, TYPE_SERVER, s.name, 0, unread, highlights, b.last_seen_eid, b.min_eid, 1, b.archived, s.status));
if(unread > 0 && firstUnreadPosition == -1)
firstUnreadPosition = position;
if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position))
lastUnreadPosition = position;
if(highlights > 0 && firstHighlightPosition == -1)
firstHighlightPosition = position;
if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position))
lastHighlightPosition = position;
position++;
break;
}
}
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
int type = -1;
int key = 0;
int joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
type = TYPE_CHANNEL;
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
if(c != null && c.mode != null && c.mode.contains("k"))
key = 1;
}
else if(b.type.equalsIgnoreCase("conversation"))
type = TYPE_CONVERSATION;
if(type > 0 && b.archived == 0) {
int unread = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
int highlights = EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid);
if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(disabledMap.has(String.valueOf(b.bid)) && disabledMap.getBoolean(String.valueOf(b.bid)))
unread = 0;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, key, unread, highlights, b.last_seen_eid, b.min_eid, joined, b.archived, s.status));
if(unread > 0 && firstUnreadPosition == -1)
firstUnreadPosition = position;
if(unread > 0 && (lastUnreadPosition == -1 || lastUnreadPosition < position))
lastUnreadPosition = position;
if(highlights > 0 && firstHighlightPosition == -1)
firstHighlightPosition = position;
if(highlights > 0 && (lastHighlightPosition == -1 || lastHighlightPosition < position))
lastHighlightPosition = position;
position++;
}
}
entries.add(adapter.buildItem(s.cid, 0, TYPE_ARCHIVES_HEADER, "Archives", 0, 0, 0, 0, 0, 0, 1, s.status));
position++;
if(mExpandArchives.get(s.cid, false)) {
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
int type = -1;
if(b.archived == 1) {
if(b.type.equalsIgnoreCase("channel"))
type = TYPE_CHANNEL;
else if(b.type.equalsIgnoreCase("conversation"))
type = TYPE_CONVERSATION;
if(type > 0) {
entries.add(adapter.buildItem(b.cid, b.bid, type, b.name, 0, 0, 0, b.last_seen_eid, b.min_eid, 0, b.archived, s.status));
position++;
}
}
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
adapter.setItems(entries);
if(getListAdapter() == null && entries.size() > 0)
setListAdapter(adapter);
else
adapter.notifyDataSetChanged();
if(entries.size() > 0 && connecting != null) {
getListView().setVisibility(View.VISIBLE);
connecting.setVisibility(View.GONE);
}
updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition());
}
}
private void updateUnreadIndicators(int first, int last) {
if(topUnreadIndicator != null) {
if(firstUnreadPosition != -1 && first >= firstUnreadPosition) {
topUnreadIndicator.setVisibility(View.VISIBLE);
topUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue);
} else {
topUnreadIndicator.setVisibility(View.GONE);
}
if((lastHighlightPosition != -1 && first >= lastHighlightPosition) ||
(firstHighlightPosition != -1 && first >= firstHighlightPosition)) {
topUnreadIndicator.setVisibility(View.VISIBLE);
topUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red);
}
}
if(bottomUnreadIndicator != null) {
if(lastUnreadPosition != -1 && last <= lastUnreadPosition) {
bottomUnreadIndicator.setVisibility(View.VISIBLE);
bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.selected_blue);
} else {
bottomUnreadIndicator.setVisibility(View.GONE);
}
if((firstHighlightPosition != -1 && last <= firstHighlightPosition) ||
(lastHighlightPosition != -1 && last <= lastHighlightPosition)) {
bottomUnreadIndicator.setVisibility(View.VISIBLE);
bottomUnreadIndicatorColor.setBackgroundResource(R.drawable.highlight_red);
}
}
}
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey("data")) {
adapter = new BufferListAdapter(this);
adapter.setItems((ArrayList<BufferListEntry>) savedInstanceState.getSerializable("data"));
setListAdapter(adapter);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.bufferslist, null);
errorMsg = (TextView)view.findViewById(R.id.errorMsg);
connecting = (RelativeLayout)view.findViewById(R.id.connecting);
topUnreadIndicator = (LinearLayout)view.findViewById(R.id.topUnreadIndicator);
topUnreadIndicator.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int scrollTo = adapter.unreadPositionAbove(getListView().getFirstVisiblePosition());
if(scrollTo > 0)
getListView().setSelection(scrollTo-1);
else
getListView().setSelection(0);
updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition());
}
});
topUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.topUnreadIndicatorColor);
bottomUnreadIndicator = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicator);
bottomUnreadIndicator.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int offset = getListView().getLastVisiblePosition() - getListView().getFirstVisiblePosition();
int scrollTo = adapter.unreadPositionBelow(getListView().getLastVisiblePosition()) - offset + 2;
if(scrollTo < adapter.getCount())
getListView().setSelection(scrollTo);
else
getListView().setSelection(adapter.getCount() - 1);
updateUnreadIndicators(getListView().getFirstVisiblePosition(), getListView().getLastVisiblePosition());
}
});
bottomUnreadIndicatorColor = (LinearLayout)view.findViewById(R.id.bottomUnreadIndicatorColor);
((ListView)view.findViewById(android.R.id.list)).setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
updateUnreadIndicators(firstVisibleItem, firstVisibleItem+visibleItemCount-1);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
return view;
}
@Override
public void onSaveInstanceState(Bundle state) {
if(adapter != null && adapter.data != null && adapter.data.size() > 0)
state.putSerializable("data", adapter.data);
}
public void onResume() {
super.onResume();
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
view.setBackgroundResource(R.drawable.disconnected_yellow);
} else {
view.setBackgroundResource(R.drawable.background_blue);
connecting.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
new RefreshTask().execute((Void)null);
}
@Override
public void onPause() {
super.onPause();
if(conn != null)
conn.removeHandler(mHandler);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnBufferSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnBufferSelectedListener");
}
}
public void onListItemClick(ListView l, View v, int position, long id) {
BufferListEntry e = (BufferListEntry)adapter.getItem(position);
String type = null;
switch(e.type) {
case TYPE_ARCHIVES_HEADER:
mExpandArchives.put(e.cid, !mExpandArchives.get(e.cid, false));
new RefreshTask().execute((Void)null);
return;
case TYPE_SERVER:
type = "console";
break;
case TYPE_CHANNEL:
type = "channel";
break;
case TYPE_CONVERSATION:
type = "conversation";
break;
}
mListener.onBufferSelected(e.cid, e.bid, e.name, e.last_seen_eid, e.min_eid, type, e.joined, e.archived, e.status);
}
private void updateReconnecting() {
if(conn.getReconnectTimestamp() > 0) {
String plural = "";
int seconds = (int)((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000);
if(seconds != 1)
plural = "s";
if(seconds < 1)
errorMsg.setText("Connecting");
else if(seconds > 10 && error != null)
errorMsg.setText(error +"\n\nReconnecting in\n" + seconds + " second" + plural);
else
errorMsg.setText("Reconnecting in\n" + seconds + " second" + plural);
if(countdownTimer != null)
countdownTimer.cancel();
countdownTimer = new Timer();
countdownTimer.schedule( new TimerTask(){
public void run() {
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
updateReconnecting();
}
});
}
countdownTimer = null;
}
}, 1000);
} else {
errorMsg.setText("Offline");
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
view.setBackgroundResource(R.drawable.disconnected_yellow);
} else {
view.setBackgroundResource(R.drawable.background_blue);
errorMsg.setText("Loading");
error = null;
}
if(conn.getState() == NetworkConnection.STATE_CONNECTING) {
errorMsg.setText("Connecting");
error = null;
}
else if(conn.getState() == NetworkConnection.STATE_DISCONNECTED)
updateReconnecting();
if(adapter != null)
adapter.notifyDataSetChanged();
break;
case NetworkConnection.EVENT_FAILURE_MSG:
IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj;
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
try {
error = o.getString("message");
if(error.equals("temp_unavailable"))
error = "Your account is temporarily unavailable";
updateReconnecting();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_BACKLOG_END:
case NetworkConnection.EVENT_USERINFO:
case NetworkConnection.EVENT_MAKESERVER:
case NetworkConnection.EVENT_STATUSCHANGED:
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_MAKEBUFFER:
case NetworkConnection.EVENT_DELETEBUFFER:
case NetworkConnection.EVENT_BUFFERMSG:
case NetworkConnection.EVENT_HEARTBEATECHO:
case NetworkConnection.EVENT_BUFFERARCHIVED:
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
case NetworkConnection.EVENT_RENAMECONVERSATION:
case NetworkConnection.EVENT_PART:
new RefreshTask().execute((Void)null);
break;
default:
break;
}
}
};
public interface OnBufferSelectedListener {
public void onBufferSelected(int cid, int bid, String name, long last_seen_eid, long min_eid, String type, int joined, int archived, String status);
}
} |
package com.maddyhome.idea.vim.option;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.List;
/**
* This is an option that accepts an arbitrary list of values
*/
public class ListOption extends TextOption
{
/**
* Creates the option
* @param name The name of the option
* @param abbrev The short name
* @param dflt The option's default values
* @param pattern A regular expression that is used to validate new values. null if no check needed
*/
ListOption(String name, String abbrev, String[] dflt, String pattern)
{
super(name, abbrev);
this.dflt = new ArrayList(Arrays.asList(dflt));
this.value = new ArrayList(this.dflt);
this.pattern = pattern;
}
/**
* Gets the value of the option as a comma separated list of values
* @return The option's value
*/
public String getValue()
{
StringBuffer res = new StringBuffer();
int cnt = 0;
for (Iterator iterator = value.iterator(); iterator.hasNext(); cnt++)
{
String s = (String)iterator.next();
if (cnt > 0)
{
res.append(",");
}
res.append(s);
}
return res.toString();
}
/**
* Gets the option's values as a list
* @return The option's values
*/
public List values()
{
return value;
}
/**
* Determines if this option has all the values listed on the supplied value
* @param val A comma separated list of values to look for
* @return True if all the supplied values are set in this option, false if not
*/
public boolean contains(String val)
{
return value.containsAll(parseVals(val));
}
/**
* Sets this option to contain just the supplied values. If any of the supplied values are invalid then this
* option is not updated at all.
* @param val A comma separated list of values
* @return True if all the supplied values were correct, false if not
*/
public boolean set(String val)
{
return set(parseVals(val));
}
/**
* Adds the supplied values to the current list of values. If any of the supplied values are invalid then this
* option is not updated at all.
* @param val A comma separated list of values
* @return True if all the supplied values were correct, false if not
*/
public boolean append(String val)
{
return append(parseVals(val));
}
/**
* Adds the supplied values to the start of the current list of values. If any of the supplied values are invalid
* then this option is not updated at all.
* @param val A comma separated list of values
* @return True if all the supplied values were correct, false if not
*/
public boolean prepend(String val)
{
return prepend(parseVals(val));
}
/**
* Removes the supplied values from the current list of values. If any of the supplied values are invalid then this
* option is not updated at all.
* @param val A comma separated list of values
* @return True if all the supplied values were correct, false if not
*/
public boolean remove(String val)
{
return remove(parseVals(val));
}
protected boolean set(ArrayList vals)
{
if (vals == null)
{
return false;
}
value = vals;
fireOptionChangeEvent();
return true;
}
protected boolean append(ArrayList vals)
{
if (vals == null)
{
return false;
}
value.addAll(vals);
fireOptionChangeEvent();
return true;
}
protected boolean prepend(ArrayList vals)
{
if (vals == null)
{
return false;
}
value.addAll(0, vals);
fireOptionChangeEvent();
return true;
}
protected boolean remove(ArrayList vals)
{
if (vals == null)
{
return false;
}
value.removeAll(vals);
fireOptionChangeEvent();
return true;
}
protected ArrayList parseVals(String val)
{
ArrayList res = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(val, ",");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken().trim();
if (pattern == null || token.matches(pattern))
{
res.add(token);
}
else
{
return null;
}
}
return res;
}
/**
* Checks to see if the current value of the option matches the default value
* @return True if equal to default, false if not
*/
public boolean isDefault()
{
return dflt.equals(value);
}
/**
* Resets the option to its default value
*/
public void resetDefault()
{
if (!dflt.equals(value))
{
value = new ArrayList(dflt);
fireOptionChangeEvent();
}
}
/**
* Gets the string representation appropriate for output to :set all
* @return The option as a string {name}={value list}
*/
public String toString()
{
StringBuffer res = new StringBuffer();
res.append(" ");
res.append(getName());
res.append("=");
res.append(getValue());
return res.toString();
}
protected ArrayList dflt;
protected ArrayList value;
protected String pattern;
} |
package com.metamolecular.mx.io.mdl;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Richard L. Apodaca <rapodaca at metamolecular.com>
*/
public class SDFileReader
{
private static String RECORD_END = "$$$$";
private static String LINEFEED = "\n";
private BufferedReader reader;
private Reader file;
private String record;
private Pattern keyPattern;
private Map<String, Pattern> keyPatterns;
public SDFileReader(String filename) throws IOException
{
record = null;
file = new FileReader(filename);
reader = new BufferedReader(file);
keyPattern = Pattern.compile("^> *?<(.*?)>", Pattern.MULTILINE);
keyPatterns = new HashMap<String, Pattern>();
try
{
nextRecord();
}
catch (Exception e)
{
throw new IOException("The file " + filename + " does not appear to be a valid SD file.");
}
}
public void close()
{
try
{
file.close();
}
catch (IOException e)
{
throw new RuntimeException("Error closing file.", e);
}
}
public boolean hasNextRecord()
{
try
{
return reader.ready();
}
catch (IOException ignore)
{
}
return false;
}
public void nextRecord()
{
StringBuffer buff = new StringBuffer();
try
{
String line = reader.readLine();
while (!RECORD_END.equals(line))
{
buff.append(line + LINEFEED);
line = reader.readLine();
}
}
catch (IOException e)
{
throw new RuntimeException("An unexpected IO error occurred while reading file.", e);
}
record = buff.toString();
}
public String getData(String key)
{
Pattern pattern = keyPatterns.get(key);
if (pattern == null)
{
pattern = Pattern.compile(".*^> *?<" + key + ">$.(.*?)$.*", Pattern.MULTILINE | Pattern.DOTALL);
keyPatterns.put(key, pattern);
}
Matcher matcher = pattern.matcher(record);
return matcher.matches() ? matcher.group(1) : "";
}
public List<String> getKeys()
{
List<String> result = new ArrayList<String>();
Matcher m = keyPattern.matcher(record);
while (m.find())
{
result.add(m.group(1));
}
return result;
}
} |
package com.oakesville.mythling;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import com.oakesville.mythling.app.Listable;
import com.oakesville.mythling.media.Item;
public class ItemListFragment extends ListFragment {
private MediaActivity mediaActivity;
private ListableListAdapter adapter;
private String path;
private int preSelIdx = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
path = getArguments().getString(MediaActivity.PATH);
preSelIdx = getArguments().getInt(MediaActivity.SEL_ITEM_INDEX);
mediaActivity = (MediaActivity) activity;
populate();
}
private void populate() {
adapter = new ListableListAdapter(mediaActivity, mediaActivity.getListables(path).toArray(new Listable[0]));
setListAdapter(adapter);
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
if (mediaActivity.getAppSettings().isFireTv()) {
getListView().setSelector(R.drawable.firetv_list_selector);
getListView().setDivider(getResources().getDrawable(android.R.drawable.divider_horizontal_bright));
getListView().setDividerHeight(1);
}
if (preSelIdx >= 0) {
// only has effect for Fire TV, which is fine
adapter.setSelection(preSelIdx);
getListView().setSelection(preSelIdx);
getListView().setItemChecked(preSelIdx, true);
getListView().requestFocus();
}
if (mediaActivity.getAppSettings().isFireTv()) {
getListView().setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
mediaActivity.getListView().requestFocus();
return true;
}
else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
int pos = getListView().getSelectedItemPosition();
getListView().performItemClick(getListAdapter().getView(pos, null, null), pos, getListAdapter().getItemId(pos));
return true;
}
}
return false;
}
});
}
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Listable sel = mediaActivity.getListables(path).get(position);
if (sel instanceof Item) {
mediaActivity.playItem((Item)sel);
return true;
} else {
return false;
}
}
});
}
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
Uri uri = new Uri.Builder().path(path).build();
Intent intent = new Intent(Intent.ACTION_VIEW, uri, mediaActivity.getApplicationContext(), MediaListActivity.class);
intent.putExtra(MediaActivity.CURRENT_TOP, listView.getFirstVisiblePosition());
View topV = listView.getChildAt(0);
intent.putExtra(MediaActivity.TOP_OFFSET, (topV == null) ? 0 : topV.getTop());
intent.putExtra(MediaActivity.SEL_ITEM_INDEX, position);
startActivity(intent);
}
} |
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import javax.servlet.http.*;
import java.util.*;
public class CmsNewResourceLink extends CmsWorkplaceDefault implements I_CmsWpConstants,I_CmsConstants {
private static final String C_PARA_KEEP_PROPERTIES = "keepproperties";
private static final String C_PARA_ADD_TO_NAV = "addtonav";
private static final int DEBUG = 0;
/**
* Overwrites the getContent method of the CmsWorkplaceDefault.<br>
* Gets the content of the new resource othertype template and processed the data input.
* @param cms The CmsObject.
* @param templateFile The lock template file
* @param elementName not used
* @param parameters Parameters of the request and the template.
* @param templateSelector Selector of the template tag to be displayed.
* @return Bytearry containing the processed data of the template.
* @exception Throws CmsException if something goes wrong.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
String error = "";
boolean checkurl = true;
String filename = null;
String link = null;
String foldername = null;
String type = null;
I_CmsSession session = cms.getRequestContext().getSession(true);
// get the document to display
CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
CmsXmlLanguageFile lang = xmlTemplateDocument.getLanguageFile();
// clear session values on first load
String initial = (String)parameters.get(C_PARA_INITIAL);
if(initial != null){
// remove all session values
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_LINK);
session.removeValue(C_PARA_VIEWFILE);
session.removeValue(C_PARA_NAVPOS);
session.removeValue(C_PARA_NAVTEXT);
session.removeValue("lasturl");
}
// get the lasturl from parameters or from session
String lastUrl = getLastUrl(cms, parameters);
if(lastUrl != null){
session.putValue("lasturl", lastUrl);
}
// get the linkname and the linkurl
filename = cms.getRequestContext().getRequest().getParameter(C_PARA_FILE);
if(filename != null) {
session.putValue(C_PARA_FILE, filename);
} else {
// try to get the value from the session, e.g. after an error
filename = (String)session.getValue(C_PARA_FILE)!=null?(String)session.getValue(C_PARA_FILE):"";
}
link = cms.getRequestContext().getRequest().getParameter(C_PARA_LINK);
if(link != null) {
session.putValue(C_PARA_LINK, link);
} else {
// try to get the value from the session, e.g. after an error
link = (String)session.getValue(C_PARA_LINK)!=null?(String)session.getValue(C_PARA_LINK):"";
}
// get the parameters
String navtitle = (String)parameters.get(C_PARA_NAVTEXT);
if(navtitle != null) {
session.putValue(C_PARA_NAVTEXT, navtitle);
} else {
// try to get the value from the session, e.g. after an error
navtitle = (String)session.getValue(C_PARA_NAVTEXT)!=null?(String)session.getValue(C_PARA_NAVTEXT):"";
}
String navpos = (String)parameters.get(C_PARA_NAVPOS);
if(navpos != null) {
session.putValue(C_PARA_NAVPOS, navpos);
} else {
// try to get the value from the session, e.g. after an error
navpos = (String)session.getValue(C_PARA_NAVPOS)!=null?(String)session.getValue(C_PARA_NAVPOS):"";
}
String dummy = (String)parameters.get(CmsNewResourceLink.C_PARA_KEEP_PROPERTIES);
if (DEBUG>0) System.out.println( "parameter " + CmsNewResourceLink.C_PARA_KEEP_PROPERTIES + ": " + dummy );
boolean keepTargetProperties = false;
if (dummy!=null) {
session.putValue(CmsNewResourceLink.C_PARA_KEEP_PROPERTIES, dummy);
}
else {
dummy = (String)session.getValue(CmsNewResourceLink.C_PARA_KEEP_PROPERTIES)!=null?(String)session.getValue(CmsNewResourceLink.C_PARA_KEEP_PROPERTIES):"true";
}
keepTargetProperties = dummy.trim().equalsIgnoreCase("true");
dummy = (String)parameters.get(CmsNewResourceLink.C_PARA_ADD_TO_NAV);
if (DEBUG>0) System.out.println( "parameter " + CmsNewResourceLink.C_PARA_ADD_TO_NAV + ": " + dummy );
boolean addToNav = false;
if (dummy!=null) {
session.putValue(CmsNewResourceLink.C_PARA_ADD_TO_NAV, dummy);
}
else {
dummy = (String)session.getValue(CmsNewResourceLink.C_PARA_ADD_TO_NAV)!=null?(String)session.getValue(CmsNewResourceLink.C_PARA_ADD_TO_NAV):"false";
}
addToNav = dummy.trim().equalsIgnoreCase("true");
String notChange = (String)parameters.get("newlink");
CmsResource linkResource = null;
String step = cms.getRequestContext().getRequest().getParameter("step");
// set the values e.g. after an error
xmlTemplateDocument.setData("LINKNAME", filename);
xmlTemplateDocument.setData("LINKVALUE", link);
xmlTemplateDocument.setData("NAVTITLE", navtitle);
xmlTemplateDocument.setData("KEEPPROPERTIES", keepTargetProperties==true ? "true" : "false" );
xmlTemplateDocument.setData("ADDTONAV", addToNav==true ? "true" : "false" );
// if an existing link should be edited show the change page
if(notChange != null && notChange.equals("false") && step == null) {
try{
CmsFile currentFile = cms.readFile(filename);
String content = new String(currentFile.getContents());
xmlTemplateDocument.setData("LINKNAME", currentFile.getName());
xmlTemplateDocument.setData("LINK", currentFile.getAbsolutePath());
xmlTemplateDocument.setData("LINKVALUE", content);
templateSelector = "change";
} catch (CmsException e){
error = e.getShortException();
}
}
// get the current phase of this wizard
if(step != null) {
// step 1 - show the final selection screen
if(step.equals("1") || step.equals("2")) {
try{
// step 1 - create the link with checking http-link
// step 2 - create the link without link check
// get folder- and filename
foldername = (String)session.getValue(C_PARA_FILELIST);
if(foldername == null) {
foldername = cms.rootFolder().getAbsolutePath();
}
String title = lang.getLanguageValue("explorer.linkto") + " " + link;
type = "link";
if(notChange != null && notChange.equals("false")) {
// change old file
CmsFile editFile = cms.readFile(filename);
editFile.setContents(link.getBytes());
if(step.equals("1")){
if(!link.startsWith("/")){
checkurl = CmsLinkCheck.checkUrl(link);
}
}
if(checkurl){
cms.writeFile(editFile);
cms.writeProperty(filename, C_PROPERTY_TITLE, title);
}
linkResource = (CmsResource)editFile;
} else {
// create the new file
Hashtable prop = new Hashtable();
prop.put(C_PROPERTY_TITLE, title);
if(step.equals("1")){
if(!link.startsWith("/")){
checkurl = CmsLinkCheck.checkUrl(link);
}
}
if(checkurl){
HashMap targetProperties = null;
if (keepTargetProperties) {
try {
targetProperties = new HashMap( cms.readAllProperties(link) );
}
catch (Exception e) {}
}
linkResource = cms.createResource( foldername + filename, type, prop, link.getBytes(), targetProperties );
}
}
// now check if navigation informations have to be added to the new page.
if(!"".equals(navtitle) && checkurl) {
cms.writeProperty(linkResource.getAbsolutePath(), C_PROPERTY_NAVTEXT, navtitle);
// update the navposition.
if(navpos != null) {
updateNavPos(cms, linkResource, navpos);
}
}
// remove values from session
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_VIEWFILE);
session.removeValue(C_PARA_LINK);
session.removeValue(C_PARA_NAVTEXT);
session.removeValue(C_PARA_NAVPOS);
// now return to appropriate filelist
} catch (CmsException e){
error = e.getShortException();
}
if(checkurl && ("".equals(error.trim()))){
try {
if(lastUrl != null) {
cms.getRequestContext().getResponse().sendRedirect(lastUrl);
} else {
cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath()
+ C_WP_EXPLORER_FILELIST);
}
} catch(Exception e) {
throw new CmsException("Redirect fails :" + getConfigFile(cms).getWorkplaceActionPath()
+ C_WP_EXPLORER_FILELIST, CmsException.C_UNKNOWN_EXCEPTION, e);
}
return null;
}
}
} else {
session.removeValue(C_PARA_FILE);
session.removeValue(C_PARA_VIEWFILE);
session.removeValue(C_PARA_LINK);
session.removeValue(C_PARA_NAVTEXT);
}
// set lasturl
if(lastUrl == null) {
lastUrl = C_WP_EXPLORER_FILELIST;
}
xmlTemplateDocument.setData("lasturl", lastUrl);
// set the templateselector if there was an error
if(!checkurl){
xmlTemplateDocument.setData("folder", foldername);
xmlTemplateDocument.setData("newlink", notChange);
session.putValue(C_PARA_LINK, link);
session.putValue(C_PARA_FILE, filename);
session.putValue(C_PARA_NAVTEXT, navtitle);
session.putValue(C_PARA_NAVPOS, navpos);
templateSelector = "errorcheckurl";
}
if(!"".equals(error.trim())){
xmlTemplateDocument.setData("errordetails", error);
session.putValue(C_PARA_LINK, link);
session.putValue(C_PARA_FILE, filename);
session.putValue(C_PARA_NAVTEXT, navtitle);
session.putValue(C_PARA_NAVPOS, navpos);
templateSelector = "error";
}
// process the selected template
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector);
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
/**
* Sets the value of the new file input field of dialog.
* This method is directly called by the content definiton.
* @param Cms The CmsObject.
* @param lang The language file.
* @param parameters User parameters.
* @return Value that is set into the new file dialod.
* @exception CmsExeption if something goes wrong.
*/
public String setValue(CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) throws CmsException {
I_CmsSession session = cms.getRequestContext().getSession(true);
// get a previous value from the session
String filename = (String)session.getValue(C_PARA_FILE);
if(filename == null) {
filename = "";
}
return filename;
}
/**
* Gets the files displayed in the navigation select box.
* @param cms The CmsObject.
* @param lang The langauge definitions.
* @param names The names of the new rescources.
* @param values The links that are connected with each resource.
* @param parameters Hashtable of parameters (not used yet).
* @returns The vectors names and values are filled with data for building the navigation.
* @exception Throws CmsException if something goes wrong.
*/
public Integer getNavPos(CmsObject cms, CmsXmlLanguageFile lang, Vector names,
Vector values, Hashtable parameters) throws CmsException {
int retValue = -1;
I_CmsSession session = cms.getRequestContext().getSession(true);
String preselect = (String)session.getValue(C_PARA_NAVPOS);
// get the nav information
Hashtable storage = getNavData(cms);
if(storage.size() > 0) {
String[] nicenames = (String[])storage.get("NICENAMES");
int count = ((Integer)storage.get("COUNT")).intValue();
// finally fill the result vectors
for(int i = 0;i <= count;i++) {
names.addElement(nicenames[i]);
values.addElement(nicenames[i]);
if ((preselect != null) && (preselect.equals(nicenames[i]))){
retValue = values.size() -1;
}
}
}
else {
values = new Vector();
}
if (retValue == -1){
// set the default value to no change
return new Integer(values.size() - 1);
}else{
return new Integer(retValue);
}
}
/**
* Gets all required navigation information from the files and subfolders of a folder.
* A file list of all files and folder is created, for all those resources, the navigation
* property is read. The list is sorted by their navigation position.
* @param cms The CmsObject.
* @return Hashtable including three arrays of strings containing the filenames,
* nicenames and navigation positions.
* @exception Throws CmsException if something goes wrong.
*/
private Hashtable getNavData(CmsObject cms) throws CmsException {
I_CmsSession session = cms.getRequestContext().getSession(true);
CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms);
String[] filenames;
String[] nicenames;
String[] positions;
Hashtable storage = new Hashtable();
CmsFolder folder = null;
CmsFile file = null;
String nicename = null;
String currentFilelist = null;
int count = 1;
float max = 0;
// get the current folder
currentFilelist = (String)session.getValue(C_PARA_FILELIST);
if(currentFilelist == null) {
currentFilelist = cms.rootFolder().getAbsolutePath();
}
// get all files and folders in the current filelist.
Vector files = cms.getFilesInFolder(currentFilelist);
Vector folders = cms.getSubFolders(currentFilelist);
// combine folder and file vector
Vector filefolders = new Vector();
Enumeration enum = folders.elements();
while(enum.hasMoreElements()) {
folder = (CmsFolder)enum.nextElement();
filefolders.addElement(folder);
}
enum = files.elements();
while(enum.hasMoreElements()) {
file = (CmsFile)enum.nextElement();
filefolders.addElement(file);
}
if(filefolders.size() > 0) {
// Create some arrays to store filename, nicename and position for the
// nav in there. The dimension of this arrays is set to the number of
// found files and folders plus two more entrys for the first and last
// element.
filenames = new String[filefolders.size() + 2];
nicenames = new String[filefolders.size() + 2];
positions = new String[filefolders.size() + 2];
//now check files and folders that are not deleted and include navigation
// information
enum = filefolders.elements();
while(enum.hasMoreElements()) {
CmsResource res = (CmsResource)enum.nextElement();
// check if the resource is not marked as deleted
if(res.getState() != C_STATE_DELETED) {
String navpos = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVPOS);
// check if there is a navpos for this file/folder
if(navpos != null) {
nicename = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVTEXT);
if(nicename == null) {
nicename = res.getName();
}
// add this file/folder to the storage.
filenames[count] = res.getAbsolutePath();
nicenames[count] = nicename;
positions[count] = navpos;
if(new Float(navpos).floatValue() > max) {
max = new Float(navpos).floatValue();
}
count++;
}
}
}
}
else {
filenames = new String[2];
nicenames = new String[2];
positions = new String[2];
}
// now add the first and last value
filenames[0] = "FIRSTENTRY";
nicenames[0] = lang.getDataValue("input.firstelement");
positions[0] = "0";
filenames[count] = "LASTENTRY";
nicenames[count] = lang.getDataValue("input.lastelement");
positions[count] = new Float(max + 1).toString();
// finally sort the nav information.
sort(cms, filenames, nicenames, positions, count);
// put all arrays into a hashtable to return them to the calling method.
storage.put("FILENAMES", filenames);
storage.put("NICENAMES", nicenames);
storage.put("POSITIONS", positions);
storage.put("COUNT", new Integer(count));
return storage;
}
/**
* Sorts a set of three String arrays containing navigation information depending on
* their navigation positions.
* @param cms Cms Object for accessign files.
* @param filenames Array of filenames
* @param nicenames Array of well formed navigation names
* @param positions Array of navpostions
*/
private void sort(CmsObject cms, String[] filenames, String[] nicenames, String[] positions, int max) {
// Sorting algorithm
// This method uses an bubble sort, so replace this with something more
// efficient
for(int i = max - 1;i > 1;i
for(int j = 1;j < i;j++) {
float a = new Float(positions[j]).floatValue();
float b = new Float(positions[j + 1]).floatValue();
if(a > b) {
String tempfilename = filenames[j];
String tempnicename = nicenames[j];
String tempposition = positions[j];
filenames[j] = filenames[j + 1];
nicenames[j] = nicenames[j + 1];
positions[j] = positions[j + 1];
filenames[j + 1] = tempfilename;
nicenames[j + 1] = tempnicename;
positions[j + 1] = tempposition;
}
}
}
}
/**
* Updates the navigation position of all resources in the actual folder.
* @param cms The CmsObject.
* @param newfile The new file added to the nav.
* @param navpos The file after which the new entry is sorted.
*/
private void updateNavPos(CmsObject cms, CmsResource newfile, String newpos) throws CmsException {
float newPos = 0;
// get the nav information
Hashtable storage = getNavData(cms);
if(storage.size() > 0) {
String[] nicenames = (String[])storage.get("NICENAMES");
String[] positions = (String[])storage.get("POSITIONS");
int count = ((Integer)storage.get("COUNT")).intValue();
// now find the file after which the new file is sorted
int pos = 0;
for(int i = 0;i < nicenames.length;i++) {
if(newpos.equals((String)nicenames[i])) {
pos = i;
}
}
if(pos < count) {
float low = new Float(positions[pos]).floatValue();
float high = new Float(positions[pos + 1]).floatValue();
newPos = (high + low) / 2;
}
else {
newPos = new Float(positions[pos]).floatValue() + 1;
}
}
else {
newPos = 1;
}
cms.writeProperty(newfile.getAbsolutePath(), C_PROPERTY_NAVPOS, new Float(newPos).toString());
}
} |
package ch.puzzle.itc.mobiliar.business.releasing.boundary;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import ch.puzzle.itc.mobiliar.business.releasing.control.ReleaseRepository;
import ch.puzzle.itc.mobiliar.business.releasing.entity.ReleaseEntity;
import ch.puzzle.itc.mobiliar.business.resourcegroup.entity.ResourceGroupEntity;
import ch.puzzle.itc.mobiliar.business.security.entity.Permission;
import ch.puzzle.itc.mobiliar.business.security.interceptor.HasPermission;
import static ch.puzzle.itc.mobiliar.business.security.entity.Action.DELETE;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class ReleaseLocator {
@Inject
protected Logger log;
@Inject
ReleaseRepository releaseRepository;
public ReleaseEntity getReleaseByName(String name) {
return releaseRepository.getReleaseByName(name);
}
public ReleaseEntity getReleaseById(Integer id) {
return releaseRepository.find(id);
}
public List<ReleaseEntity> getReleasesForResourceGroup(ResourceGroupEntity resourceGroup) {
return releaseRepository.getReleasesForResourceGroup(resourceGroup);
}
@HasPermission(permission = Permission.RELEASE, action = DELETE)
public void delete(ReleaseEntity release) {
releaseRepository.removeRelease(release);
}
} |
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.enumTypes.ClockType;
import dr.app.beauti.enumTypes.FixRateType;
import dr.app.beauti.enumTypes.PriorType;
import dr.app.beauti.enumTypes.TreePriorType;
import dr.app.beauti.options.*;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.util.XMLWriter;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.clock.ACLikelihood;
import dr.evomodel.coalescent.CoalescentLikelihood;
import dr.evomodel.coalescent.GMRFFixedGridImportanceSampler;
import dr.evomodel.speciation.SpeciationLikelihood;
import dr.evomodel.speciation.SpeciesTreeModel;
import dr.evomodel.speciation.TreePartitionCoalescent;
import dr.evomodel.tree.MonophylyStatistic;
import dr.evomodel.tree.TMRCAStatistic;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.*;
import dr.evoxml.*;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.inference.loggers.Columns;
import dr.inference.model.*;
import dr.inference.operators.SimpleOperatorSchedule;
import dr.inference.xml.LoggerParser;
import dr.inferencexml.PriorParsers;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.XMLParser;
import java.io.Writer;
import java.util.*;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private final static String TREE_FILE_LOG = "treeFileLog";
private final static String SUB_TREE_FILE_LOG = "substTreeFileLog";
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final SubstitutionModelGenerator substitutionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final STARBEASTGenerator starEASTGeneratorGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
starEASTGeneratorGenerator = new STARBEASTGenerator(options, components);
}
public void checkOptions() throws IllegalArgumentException {
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new IllegalArgumentException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new IllegalArgumentException("A taxon has the same id," + taxon.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (Taxa taxa : options.taxonSets) {
if (taxa.getTaxonCount() < 2) {
throw new IllegalArgumentException("Taxon set, " + taxa.getId() + ", should contain\n" +
"at least two taxa.");
}
if (ids.contains(taxa.getId())) {
throw new IllegalArgumentException("A taxon sets has the same id," + taxa.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxa.getId());
}
//++++++++++++++++ Tree Prior ++++++++++++++++++
if (options.isShareSameTreePrior()) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePriorType.GMRF_SKYRIDE) {
throw new IllegalArgumentException("For GMRF, tree model/tree prior combination not implemented by BEAST yet!" +
"\nPlease uncheck the shareSameTreePrior if using GMRF.");
}
}
}
//++++++++++++++++ clock model/tree model combination ++++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// clock model/tree model combination not implemented by BEAST yet
validateClockTreeModelCombination(model);
}
//++++++++++++++++ Species tree ++++++++++++++++++
if (options.starBEASTOptions.isSpeciesAnalysis()) {
// if (!(options.nodeHeightPrior == TreePriorType.SPECIES_BIRTH_DEATH || options.nodeHeightPrior == TreePriorType.SPECIES_YULE)) {
// //TODO: more species tree model
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param w the writer
*/
public void generateXML(Writer w) {
XMLWriter writer = new XMLWriter(w);
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString());
writer.writeComment(" by Alexei J. Drummond and Andrew Rambaut");
writer.writeComment(" Department of Computer Science, University of Auckland and");
writer.writeComment(" Institute of Evolutionary Biology, University of Edinburgh");
writer.writeComment(" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
//++++++++++++++++ Taxon List ++++++++++++++++++
writeTaxa(writer, options.taxonList);
List<Taxa> taxonSets = options.taxonSets;
if (taxonSets != null && taxonSets.size() > 0) {
writeTaxonSets(writer, taxonSets); // TODO
}
if (options.allowDifferentTaxa) { // allow diff taxa for multi-gene
writer.writeText("");
writer.writeComment("List all taxons regarding each gene (file) for Multispecies Coalescent function");
// write all taxa in each gene tree regarding each data partition,
for (PartitionData partition : options.dataPartitions) {
// do I need if (!alignments.contains(alignment)) {alignments.add(alignment);} ?
writeDifferentTaxaForMultiGene(partition, writer);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
//++++++++++++++++ Alignments ++++++++++++++++++
List<Alignment> alignments = new ArrayList<Alignment>();
for (PartitionData partition : options.dataPartitions) {
Alignment alignment = partition.getAlignment();
if (!alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (!options.samplePriorOnly) {
int index = 1;
for (Alignment alignment : alignments) {
if (alignments.size() > 1) {
//if (!options.allowDifferentTaxa) {
alignment.setId(AlignmentParser.ALIGNMENT + index);
//} else { // e.g. alignment_gene1
// alignment.setId("alignment_" + mulitTaxaTagName + index);
} else {
alignment.setId(AlignmentParser.ALIGNMENT);
}
writeAlignment(alignment, writer);
index += 1;
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
//++++++++++++++++ Pattern Lists ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// writePatternList(model, writer);
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
writePatternList(partition, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
} else {
Alignment alignment = alignments.get(0);
alignment.setId(AlignmentParser.ALIGNMENT);
writeAlignment(alignment, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
}
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePriorModel(options.activedSameTreePrior, writer);
// } else { // Different Tree Priors
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.constant
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
//++++++++++++++++ Starting Tree ++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// initialTreeGenerator.setModelPrefix("");
// initialTreeGenerator.writeStartingTree(options.getPartitionTreeModels().get(0), writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// initialTreeGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
//++++++++++++++++ Tree Model +++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// treeModelGenerator.setModelPrefix("");
// treeModelGenerator.writeTreeModel(writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// treeModelGenerator.setModelPrefix(model.getPrefix()); // treemodel.treeModel
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
//++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePrior(options.activedSameTreePrior, writer);
// } else { // no species
// for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.treeModel
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihood(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographic(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
// if ( options.getPartitionClockModels().size() == 1 ) { // 1 Partition Clock Model
// branchRatesModelGenerator.setModelPrefix("");
// branchRatesModelGenerator.writeBranchRatesModel(writer);
// } else { // Different Tree Models
for (PartitionClockModel model : options.getPartitionClockModels()) {
// branchRatesModelGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
// for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
branchRatesModelGenerator.writeBranchRatesModel(model, writer);
writer.writeText("");
}
// write allClockRate for fix mean option in clock model panel
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allClockRates")});
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeAllClockRateRefs(model, writer);
}
writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
writer.writeText("");
}
//++++++++++++++++ Substitution Model ++++++++++++++++++
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
//++++++++++++++++ Site Model ++++++++++++++++++
boolean writeMuParameters = options.substitutionModelOptions.hasCodon(); //options.getTotalActivePartitionSubstitutionModelCount() > 1;
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSiteModel(model, writeMuParameters, writer);
writer.writeText("");
}
if (writeMuParameters) { // write allMus for codon model
// allMus is global
writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allMus")});
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeMuParameterRefs(model, writer);
}
writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// if ( options.isSpeciesAnalysis() ) { // species
// treeLikelihoodGenerator.setModelPrefix(model.getName() + ".");
// } else {
// treeLikelihoodGenerator.setModelPrefix("");
// //TODO: need merge genePrifx and prefix
//// for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
// writer.writeText("");
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
treeLikelihoodGenerator.writeTreeLikelihood(partition, writer);
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
//++++++++++++++++ Traits ++++++++++++++++++
// traits tag
if (options.selecetedTraits.size() > 0) {
for (String trait : options.selecetedTraits) {
TraitGuesser.TraitType traiType = options.traitTypes.get(trait);
writeTraits(writer, trait, traiType.toString(), options.taxonList);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
}
if (taxonSets != null && taxonSets.size() > 0) {
//TODO: need to suit for multi-gene-tree
writeTMRCAStatistics(writer);
}
//++++++++++++++++ Operators ++++++++++++++++++
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
//++++++++++++++++ MCMC ++++++++++++++++++
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
writer.writeCloseTag("beast");
writer.flush();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
*/
private void writeTaxa(XMLWriter writer, TaxonList taxonList) {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa analyse (can also include dates/ages).");
writer.writeComment("ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.clockModelOptions.isTipCalibrated()) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
writer.writeTag(TaxonParser.TAXON, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, taxon.getId())}, !hasDate);
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
Attribute[] attributes = {
new Attribute.Default<Double>(ParameterParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>("direction", date.isBackwards() ? "backwards" : "forwards"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
/*,
new Attribute.Default("origin", date.getOrigin()+"")*/
};
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
writer.writeCloseTag(TaxonParser.TAXON);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate additional taxon sets
*
* @param writer the writer
* @param taxonSets a list of taxa to write
*/
private void writeTaxonSets(XMLWriter writer, List<Taxa> taxonSets) {
writer.writeText("");
for (Taxa taxa : taxonSets) {
writer.writeOpenTag(
TaxaParser.TAXA,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxa.getId())
}
);
for (int j = 0; j < taxa.getTaxonCount(); j++) {
writer.writeIDref(TaxonParser.TAXON, taxa.getTaxon(j).getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
}
/**
* Determine and return the datatype description for these beast options
* note that the datatype in XML may differ from the actual datatype
*
* @param alignment the alignment to get data type description of
* @return description
*/
private String getAlignmentDataTypeDescription(Alignment alignment) {
String description;
switch (alignment.getDataType().getType()) {
case DataType.TWO_STATES:
case DataType.COVARION:
// TODO make this work
// throw new RuntimeException("TO DO!");
//switch (partition.getPartitionSubstitutionModel().binarySubstitutionModel) {
// case ModelOptions.BIN_COVARION:
// description = TwoStateCovarion.DESCRIPTION;
// break;
// default:
description = alignment.getDataType().getDescription();
break;
default:
description = alignment.getDataType().getDescription();
}
return description;
}
public void writeDifferentTaxaForMultiGene(PartitionData dataPartition, XMLWriter writer) {
String data = dataPartition.getName();
Alignment alignment = dataPartition.getAlignment();
writer.writeComment("gene name = " + data + ", ntax= " + alignment.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, data + "." + TaxaParser.TAXA)});
for (int i = 0; i < alignment.getTaxonCount(); i++) {
final Taxon taxon = alignment.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate an alignment block from these beast options
*
* @param alignment the alignment to write
* @param writer the writer
*/
public void writeAlignment(Alignment alignment, XMLWriter writer) {
writer.writeText("");
writer.writeComment("The sequence alignment (each sequence refers to a taxon above).");
writer.writeComment("ntax=" + alignment.getTaxonCount() + " nchar=" + alignment.getSiteCount());
if (options.samplePriorOnly) {
writer.writeComment("Null sequences generated in order to sample from the prior only.");
}
writer.writeOpenTag(
AlignmentParser.ALIGNMENT,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, alignment.getId()),
new Attribute.Default<String>("dataType", getAlignmentDataTypeDescription(alignment))
}
);
for (int i = 0; i < alignment.getTaxonCount(); i++) {
Taxon taxon = alignment.getTaxon(i);
writer.writeOpenTag("sequence");
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
if (!options.samplePriorOnly) {
writer.writeText(alignment.getAlignedSequenceString(i));
} else {
writer.writeText("N");
}
writer.writeCloseTag("sequence");
}
writer.writeCloseTag(AlignmentParser.ALIGNMENT);
}
/**
* Generate traits block regarding specific trait name (currently only <species>) from options
*
* @param writer
* @param trait
* @param traitType
* @param taxonList
*/
private void writeTraits(XMLWriter writer, String trait, String traitType, TaxonList taxonList) {
writer.writeText("");
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
writer.writeComment("Species definition: binds taxa, species and gene trees");
}
writer.writeComment("trait = " + trait + " trait_type = " + traitType);
writer.writeOpenTag(trait, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, trait)});
//new Attribute.Default<String>("traitType", traitType)});
// write sub-tags for species
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeMultiSpecies(taxonList, writer);
} // end write sub-tags for species
writer.writeCloseTag(trait);
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeSTARBEAST(writer);
}
}
/**
* Writes the pattern lists
*
* @param partition the partition data to write the pattern lists for
* @param writer the writer
*/
public void writePatternList(PartitionData partition, XMLWriter writer) {
writer.writeText("");
PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel();
String codonHeteroPattern = model.getCodonHeteroPattern();
int partitionCount = model.getCodonPartitionCount();
if (model.getDataType() == Nucleotides.INSTANCE && codonHeteroPattern != null && partitionCount > 1) {
if (codonHeteroPattern.equals("112")) {
writer.writeComment("The unique patterns for codon positions 1 & 2");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(1) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 0, 3, writer);
writePatternList(partition, 1, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
writer.writeComment("The unique patterns for codon positions 3");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(2) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 2, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
} else {
// pattern is 123
// write pattern lists for all three codon positions
for (int i = 1; i <= 3; i++) {
writer.writeComment("The unique patterns for codon positions " + i);
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(i) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, i - 1, 3, writer);
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
} else {
//partitionCount = 1;
// writer.writeComment("The unique patterns site patterns");
// Alignment alignment = partition.getAlignment();
// writer.writeOpenTag(SitePatternsParser.PATTERNS,
// new Attribute[]{
// new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS),
writePatternList(partition, 0, 1, writer);
// writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
// writer.writeCloseTag(SitePatternsParser.PATTERNS);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
// writePatternList(partition, 0, 1, writer);
}
}
/**
* Write a single pattern list
*
* @param partition the partition to write a pattern list for
* @param offset offset by
* @param every skip every
* @param writer the writer
*/
private void writePatternList(PartitionData partition, int offset, int every, XMLWriter writer) {
Alignment alignment = partition.getAlignment();
int from = partition.getFromSite();
int to = partition.getToSite();
int partEvery = partition.getEvery();
if (partEvery > 1 && every > 1) throw new IllegalArgumentException();
if (from < 1) from = 1;
every = Math.max(partEvery, every);
from += offset;
writer.writeComment("The unique patterns from " + from + " to " + (to > 0 ? to : "end") + ((every > 1) ? " every " + every : ""));
// this object is created solely to calculate the number of patterns in the alignment
SitePatterns patterns = new SitePatterns(alignment, from - 1, to - 1, every);
writer.writeComment("npatterns=" + patterns.getPatternCount());
List<Attribute> attributes = new ArrayList<Attribute>();
// no codon, unique patterns site patterns
if (offset == 0 && every == 1)
attributes.add(new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS));
attributes.add(new Attribute.Default<String>("from", "" + from));
if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
if (every > 1) {
attributes.add(new Attribute.Default<String>("every", "" + every));
}
// generate <patterns>
writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
}
/**
* Generate tmrca statistics
*
* @param writer the writer
*/
public void writeTMRCAStatistics(XMLWriter writer) {
writer.writeText("");
for (Taxa taxa : options.taxonSets) {
writer.writeOpenTag(
TMRCAStatistic.TMRCA_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "tmrca(" + taxa.getId() + ")"),
}
);
writer.writeOpenTag(TMRCAStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(TMRCAStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(TMRCAStatistic.TMRCA_STATISTIC);
if (options.taxonSetsMono.get(taxa)) {
writer.writeOpenTag(
MonophylyStatistic.MONOPHYLY_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "monophyly(" + taxa.getId() + ")"),
});
writer.writeOpenTag(MonophylyStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(MonophylyStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(MonophylyStatistic.MONOPHYLY_STATISTIC);
}
}
}
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("mcmc", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
*
* @param writer
*/
public void writeMCMC(XMLWriter writer) {
writer.writeComment("Define MCMC");
writer.writeOpenTag(
"mcmc",
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "mcmc"),
new Attribute.Default<Integer>("chainLength", options.chainLength),
new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false")
});
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihood.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihood.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
writeParameterPriors(writer);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographicReference(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihood.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihood.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihood.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihood.POSTERIOR);
}
writer.writeIDref(SimpleOperatorSchedule.OPERATOR_SCHEDULE, "operators");
// write log to screen
writeLogToScreen(writer);
// write log to file
writeLogToFile(writer);
// write tree log to file
writeTreeLogToFile(writer);
writer.writeCloseTag("mcmc");
}
/**
* write log to screen
*
* @param writer
*/
private void writeLogToScreen(XMLWriter writer) {
writer.writeComment("write log to screen");
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "screenLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.echoEvery + "")
});
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Posterior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Prior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
writer.writeCloseTag(Columns.COLUMN);
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Likelihood"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
writer.writeCloseTag(Columns.COLUMN);
}
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "PopMean"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Root Height"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
writer.writeCloseTag(Columns.COLUMN);
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Rate"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
writer.writeIDref(ParameterParser.PARAMETER, "allClockRates");
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.UNCORRELATED_LOGNORMAL)
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
}
} else {
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeLog(model, writer);
}
}
writer.writeCloseTag(Columns.COLUMN);
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeLogStatistic(model, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_SCREEN_LOG, writer);
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SCREEN_LOG, writer);
}
/**
* write log to file
*
* @param writer
*/
private void writeLogToFile(XMLWriter writer) {
writer.writeComment("write log to file");
if (options.logFileName == null) {
options.logFileName = options.fileNameStem + ".log";
}
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "fileLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName)
});
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
}
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
}
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.starBEASTOptions.POP_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, SpeciesTreeModel.SPECIES_TREE + "." + SPLIT_POPS);
if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_BIRTH_DEATH) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
} else if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE);
} else {
throw new IllegalArgumentException("Get wrong species tree prior using *BEAST : " + options.getPartitionTreePriors().get(0).getNodeHeightPrior().toString());
}
//Species Tree: tmrcaStatistic
writer.writeIDref(TMRCAStatistic.TMRCA_STATISTIC, SpeciesTreeModel.SPECIES_TREE + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
for (Taxa taxa : options.taxonSets) {
writer.writeIDref("tmrcaStatistic", "tmrca(" + taxa.getId() + ")");
}
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeParameterLog(options.activedSameTreePrior, writer);
// } else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // priorName.treeModel
treePriorGenerator.writeParameterLog(prior, writer);
}
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeLog(writer, model);
}
if (options.substitutionModelOptions.hasCodon()) {
writer.writeIDref(ParameterParser.PARAMETER, "allMus");
}
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.FIX_MEAN) {
writer.writeIDref(ParameterParser.PARAMETER, "allClockRates");
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.UNCORRELATED_LOGNORMAL)
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
}
} else {
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeLog(model, writer);
}
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeLogStatistic(model, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);
if (options.hasData()) {
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);
// coalescentLikelihood
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihoodReferenceLog(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePriorType.EXTENDED_SKYLINE)
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, prior.getPrefix() + COALESCENT); // only 1 coalescent
}
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
}
/**
* write tree log to file
*
* @param writer
*/
private void writeTreeLogToFile(XMLWriter writer) {
writer.writeComment("write tree log to file");
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
// species tree log
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TraitGuesser.Traits.TRAIT_SPECIES + "." + TREE_FILE_LOG), // speciesTreeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + options.starBEASTOptions.SPECIES_TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
// gene tree log
//TODO make code consistent to MCMCPanel
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
String treeFileName;
if (options.substTreeLog) {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + "(time)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
} else {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + GMRFFixedGridImportanceSampler.TREE_FILE_NAME; // stem.partitionName.tree
}
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG)); // partionName.treeFileLog
attributes.add(new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName));
attributes.add(new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true"));
if (options.clockModelOptions.getRateOptionClockModel() == FixRateType.RElATIVE_TO) {
double aveFixedRate = options.clockModelOptions.getSelectedRate(options.getPartitionClockModels());
attributes.add(new Attribute.Default<String>(TreeLoggerParser.NORMALISE_MEAN_RATE_TO, Double.toString(aveFixedRate)));
}
// generate <logTree>
writer.writeOpenTag(TreeLoggerParser.LOG_TREE, attributes);
// writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
// new Attribute[]{
// new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG), // partionName.treeFileLog
// new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
// new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
// new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName),
// new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
} // end For loop
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREES_LOG, writer);
if (options.substTreeLog) {
if (options.starBEASTOptions.isSpeciesAnalysis()) { // species
//TODO: species sub tree
}
// gene tree
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
// write tree log to file
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + tree.getPrefix() +
"(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREES_LOG, writer);
}
/**
* Write the priors for each parameter
*
* @param writer the writer
*/
private void writeParameterPriors(XMLWriter writer) {
boolean first = true;
for (Map.Entry<Taxa, Boolean> taxaBooleanEntry : options.taxonSetsMono.entrySet()) {
if (taxaBooleanEntry.getValue()) {
if (first) {
writer.writeOpenTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
first = false;
}
final String taxaRef = "monophyly(" + taxaBooleanEntry.getKey().getId() + ")";
writer.writeIDref(MonophylyStatistic.MONOPHYLY_STATISTIC, taxaRef);
}
}
if (!first) {
writer.writeCloseTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
}
ArrayList<Parameter> parameters = options.selectParameters();
for (Parameter parameter : parameters) {
if (parameter.priorType != PriorType.NONE) {
if (parameter.priorType != PriorType.UNIFORM_PRIOR || parameter.isNodeHeight) {
writeParameterPrior(parameter, writer);
}
}
}
}
/**
* Write the priors for each parameter
*
* @param parameter the parameter
* @param writer the writer
*/
private void writeParameterPrior(dr.app.beauti.options.Parameter parameter, XMLWriter writer) {
switch (parameter.priorType) {
case UNIFORM_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
break;
case EXPONENTIAL_PRIOR:
writer.writeOpenTag(PriorParsers.EXPONENTIAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.exponentialMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.exponentialOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.EXPONENTIAL_PRIOR);
break;
case NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
case LOGNORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.LOG_NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.logNormalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.logNormalStdev),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.logNormalOffset),
// this is to be implemented...
new Attribute.Default<String>(PriorParsers.MEAN_IN_REAL_SPACE, "false")
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.LOG_NORMAL_PRIOR);
break;
case GAMMA_PRIOR:
writer.writeOpenTag(PriorParsers.GAMMA_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.gammaAlpha),
new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.gammaBeta),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.gammaOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.GAMMA_PRIOR);
break;
case JEFFREYS_PRIOR:
writer.writeOpenTag(OneOnXPrior.ONE_ONE_X_PRIOR);
writeParameterIdref(writer, parameter);
writer.writeCloseTag(OneOnXPrior.ONE_ONE_X_PRIOR);
break;
case POISSON_PRIOR:
writer.writeOpenTag(PriorParsers.POISSON_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.poissonMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.poissonOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.POISSON_PRIOR);
break;
case TRUNC_NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
default:
throw new IllegalArgumentException("Unknown priorType");
}
}
private void writeParameterIdref(XMLWriter writer, dr.app.beauti.options.Parameter parameter) {
if (parameter.isStatistic) {
writer.writeIDref("statistic", parameter.getName());
} else {
writer.writeIDref(ParameterParser.PARAMETER, parameter.getName());
}
}
} |
/**
* No Rights Reserved.
* This program and the accompanying materials
* are made available under the terms of the Public Domain.
*/
package logbook.thread;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public final class ThreadStateObserver extends Thread {
private final Shell shell;
private final List<Thread> observthread;
public ThreadStateObserver(Shell shell) {
this.observthread = ThreadManager.getThreads();
this.shell = shell;
}
/* ( Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
while (true) {
for (int i = 0; i < this.observthread.size(); i++) {
Thread target = this.observthread.get(i);
if (!target.isAlive()) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append("[");
sb.append(target.getName());
sb.append("]");
sb.append("\n");
sb.append(":\n");
sb.append(ThreadManager.getUncaughtExceptionHandler(target));
final String message = sb.toString();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MessageBox box = new MessageBox(ThreadStateObserver.this.shell, SWT.YES
| SWT.ICON_ERROR);
box.setText("");
box.setMessage(message);
box.open();
}
});
this.observthread.remove(i);
}
}
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
package com.sebnarware.avalanche;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
@SuppressLint("SetJavaScriptEnabled")
public class WebViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// enable progress bar for loading, part 1
// NOTE must happen before content is added
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
WebView webView = (WebView) findViewById(R.id.webview);
// set a reasonable zoom and view mode
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
webView.getSettings().setBuiltInZoomControls(true);
// make link navigation stay within this webview, vs. launching the browser
webView.setWebViewClient(new WebViewClient());
// enable javascript
webView.getSettings().setJavaScriptEnabled(true);
// enable progress bar for loading, part 2
final Activity self = this;
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// NOTE activities and webviews measure progress with different scales;
// the progress meter will automatically disappear when we reach 100%
self.setProgress(progress * 1000);
}
});
// NOTE set our user agent string to something benign and non-mobile looking, to work around website
// popups from nwac.us asking if you would like to be redirected to the mobile version of the site
webView.getSettings().setUserAgentString("Mozilla/5.0");
// get the desired url from the intent
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.INTENT_EXTRA_WEB_VIEW_URL);
// set cache mode, depending on current network availability
if (NetworkEngine.isNetworkAvailable(this)){
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
} else {
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
webView.loadUrl(url);
}
} |
package dr.app.realtime;
import dr.evolution.alignment.PatternList;
import dr.evolution.alignment.Patterns;
import dr.evolution.tree.BranchRates;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.Taxon;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.tree.TreeParameterModel;
import dr.evomodel.treedatalikelihood.BeagleDataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.DataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.MultiPartitionDataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.TreeDataLikelihood;
import dr.inference.model.Likelihood;
import java.util.ArrayList;
import java.util.List;
/**
* @author Guy Baele
*/
public class CheckPointTreeModifier {
public final static String TREE_UPDATE_OPTION = "JC69Distance";
public final static Double EPSILON = 0.10;
private TreeModel treeModel;
private ArrayList<String> newTaxaNames;
private int[] nodeMap;
private int additionalTaxa;
public CheckPointTreeModifier(TreeModel treeModel) {
this.treeModel = treeModel;
}
/**
* Modifies the current tree by adopting the provided collection of edges and the stored update criterion.
* @param edges Edges are provided as index: child number; parent: array entry
* @param nodeHeights Also sets the node heights to the provided values
* @param childOrder Array that contains whether a child node is left or right child
* @param taxaNames Taxa names as stored in the checkpoint file
*/
public void adoptTreeStructure(int[] edges, double[] nodeHeights, int[] childOrder, String[] taxaNames) {
this.additionalTaxa = treeModel.getExternalNodeCount() - taxaNames.length;
//check if the taxa are in the right order, i.e. for now only allow adding taxa at the end of the list
boolean correctOrder = checkTaxaOrder(taxaNames);
if (!correctOrder) {
//create a map between the old node order and the new node order
createNodeMap(taxaNames);
}
treeModel.beginTreeEdit();
int currentTaxa = treeModel.getExternalNodeCount();
System.out.println("#external nodes = " + currentTaxa);
//first remove all the child nodes of the internal nodes
for (int i = treeModel.getExternalNodeCount(); i < treeModel.getNodeCount(); i++) {
int childCount = treeModel.getChildCount(treeModel.getNodes()[i]);
for (int j = 0; j < childCount; j++) {
treeModel.removeChild(treeModel.getNodes()[i], treeModel.getChild(treeModel.getNodes()[i], j));
}
}
//use node mapping to reconstruct the checkpointed tree
//disregard the added taxa for now
//start with setting the external node heights
//this.additionalTaxa can function as the offset in the internal node array
for (int i = 0; i < (treeModel.getExternalNodeCount()-additionalTaxa); i++) {
treeModel.setNodeHeight(treeModel.getExternalNode(nodeMap[i]), nodeHeights[i]);
}
//set the internal node heights
//this.additionalTaxa can function as the offset in the internal node array
for (int i = 0; i < (treeModel.getExternalNodeCount()-additionalTaxa-1); i++) {
//No just restart counting, will fix later on in the code by adding additionalTaxa variable
treeModel.setNodeHeight(treeModel.getInternalNode(i), nodeHeights[treeModel.getExternalNodeCount()-additionalTaxa+i]);
}
int newRootIndex = -1;
//now add the parent-child links again to ALL the nodes
for (int i = 0; i < edges.length; i++) {
if (edges[i] != -1) {
//make distinction between external nodes and internal nodes
if (i < (treeModel.getExternalNodeCount()-additionalTaxa)) {
//external node
treeModel.addChild(treeModel.getNode(edges[i]+additionalTaxa), treeModel.getExternalNode(nodeMap[i]));
System.out.println("external: " + (edges[i]+additionalTaxa) + " > " + nodeMap[i]);
} else {
//internal node
treeModel.addChild(treeModel.getNode(edges[i]+additionalTaxa), treeModel.getNode(i+additionalTaxa));
System.out.println("internal: " + (edges[i]+additionalTaxa) + " > " + (i+additionalTaxa));
}
} else {
newRootIndex = i;
}
}
//not possible to determine correct ordering of child nodes in the loop where they're being assigned
//hence perform possible swaps in a separate loop
for (int i = 0; i < edges.length; i++) {
if (edges[i] != -1) {
if (i < (treeModel.getExternalNodeCount()-additionalTaxa)) {
if (childOrder[i] == 0 && treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0) != treeModel.getExternalNode(nodeMap[i])) {
NodeRef childOne = treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0);
NodeRef childTwo = treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 1);
treeModel.removeChild(treeModel.getNode(edges[i] + additionalTaxa), childOne);
treeModel.removeChild(treeModel.getNode(edges[i] + additionalTaxa), childTwo);
treeModel.addChild(treeModel.getNode(edges[i] + additionalTaxa), childTwo);
treeModel.addChild(treeModel.getNode(edges[i] + additionalTaxa), childOne);
System.out.println(i + ": " + edges[i]);
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0));
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 1));
}
} else {
if (childOrder[i] == 0 && treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0) != treeModel.getNode(i + additionalTaxa)) {
NodeRef childOne = treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0);
NodeRef childTwo = treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 1);
treeModel.removeChild(treeModel.getNode(edges[i] + additionalTaxa), childOne);
treeModel.removeChild(treeModel.getNode(edges[i] + additionalTaxa), childTwo);
treeModel.addChild(treeModel.getNode(edges[i] + additionalTaxa), childTwo);
treeModel.addChild(treeModel.getNode(edges[i] + additionalTaxa), childOne);
System.out.println(i + ": " + edges[i]);
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0));
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 1));
}
}
}
}
System.out.println("new root index: " + newRootIndex);
treeModel.setRoot(treeModel.getNode(newRootIndex+additionalTaxa));
System.out.println(treeModel.toString());
for (int i = 0; i < edges.length; i++) {
if (edges[i] != -1) {
System.out.println(i + ": " + edges[i]);
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 0));
System.out.println(" " + treeModel.getChild(treeModel.getNode(edges[i] + additionalTaxa), 1));
}
}
treeModel.endTreeEdit();
}
/**
* Imports trait information from a file
* @param edges Edges are provided as index: child number; parent: array entry
* @param traitModels List of TreeParameterModel object that contain trait information
* @param traitValues Values to be copied into the List of TreeParameterModel objects
*/
//TODO Small difference in reconstructed log likelihood, probably due to increased number of rate categories
public void adoptTraitData(int[] edges, ArrayList<TreeParameterModel> traitModels, double[][] traitValues) {
int index = 0;
for (TreeParameterModel tpm : traitModels) {
int k = 0;
for (int i = 0; i < edges.length; i++) {
System.out.println(i + " " + edges[i]);
if (edges[i] != -1) {
//TODO Seems like I messed up here
if (i < (treeModel.getExternalNodeCount()-additionalTaxa)) {
tpm.setNodeValue(this.treeModel, this.treeModel.getExternalNode(nodeMap[i]), traitValues[index][k]);
System.out.println("Setting external node " + this.treeModel.getExternalNode(nodeMap[i]) + " to " + traitValues[index][k]);
} else {
tpm.setNodeValue(this.treeModel, this.treeModel.getNode(i + additionalTaxa), traitValues[index][k]);
System.out.println("Setting internal node " + this.treeModel.getNode(i + additionalTaxa) + " to " + traitValues[index][k]);
}
} else {
k
}
k++;
}
//set trait of remaining internal nodes to -1.0
for (int i = 0; i < additionalTaxa; i++) {
tpm.setNodeValue(this.treeModel, treeModel.getNode(treeModel.getNodeCount()-1-i), -1.0);
}
//set trait of newly added external taxa to -1.0
int shift = 0;
for (int i = 0; i < (treeModel.getExternalNodeCount()-additionalTaxa); i++) {
System.out.println("i = " + i + " ; nodeMap[i] = " + nodeMap[i]);
}
System.out.println();
for (String name : newTaxaNames) {
System.out.println("new taxon: " + name);
}
int externalMissing = 0;
for (String name : newTaxaNames) {
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
if (treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId().equals(name)) {
externalMissing++;
tpm.setNodeValue(this.treeModel, this.treeModel.getExternalNode(i), -1.0);
}
}
}
System.out.println("External nodes with trait set to -1.0 = " + externalMissing + "\n");
/*for (int i = 0; i < (treeModel.getExternalNodeCount()-additionalTaxa); i++) {
System.out.println("i = " + i + " ; nodeMap[i] = " + nodeMap[i]);
if (i != (nodeMap[i]-shift)) {
int difference = nodeMap[i] - i;
shift = difference;
tpm.setNodeValue(this.treeModel, this.treeModel.getExternalNode(nodeMap[i]-1), -1.0);
System.out.println("Setting external node: " + (nodeMap[i]-1));
externalMissing++;
}
}
System.out.println("External node with trait set to -1.0 = " + externalMissing);
index++;*/
}
}
/**
* The newly added taxa still need to be provided with trait values if there are any.
* @param traitModels List of the trait models for which trait values need to be imputed / interpolated.
*/
public void interpolateTraitValues(ArrayList<TreeParameterModel> traitModels) {
System.out.println();
for (TreeParameterModel tpm : traitModels) {
int numberOfInterpolations = 0;
for (int i = 0; i < treeModel.getNodeCount(); i++) {
if (tpm.getNodeValue(treeModel, treeModel.getNode(i)) == -1.0) {
System.out.println("Current trait = -1.0 for node: " + treeModel.getNode(i));
numberOfInterpolations++;
double newValue = -1.0;
//get trait value from sibling
NodeRef parent = treeModel.getParent(treeModel.getNode(i));
for (int j = 0; j < treeModel.getChildCount(parent); j++) {
NodeRef child = treeModel.getChild(parent, j);
if (tpm.getNodeValue(treeModel, child) != -1.0) {
tpm.setNodeValue(treeModel, treeModel.getNode(i), tpm.getNodeValue(treeModel, child) + 1.0);
System.out.println("Checking sibling trait.");
System.out.println("Setting node trait for node " + treeModel.getNode(i) + " to " + tpm.getNodeValue(treeModel, treeModel.getNode(i)));
break;
}
}
//if not successful, get trait from its parent
if (tpm.getNodeValue(treeModel, treeModel.getNode(i)) == -1.0) {
NodeRef currentNode = treeModel.getNode(i);
//TODO Check for situations where no proper trait can be found
while (currentNode != treeModel.getRoot() && tpm.getNodeValue(treeModel, currentNode) == -1.0) {
currentNode = treeModel.getParent(currentNode);
}
tpm.setNodeValue(treeModel, treeModel.getNode(i), tpm.getNodeValue(treeModel, currentNode) + 1.0);
System.out.println("Checking parent trait.");
System.out.println("Setting node trait for node " + treeModel.getNode(i) + " to " + tpm.getNodeValue(treeModel, currentNode));
}
//adjust the other trait values after a trait has been imputed
for (int j = 0; j < treeModel.getNodeCount(); j++) {
if (treeModel.getNode(j) != treeModel.getNode(i)) {
if (tpm.getNodeValue(treeModel, treeModel.getNode(j)) >= tpm.getNodeValue(treeModel, treeModel.getNode(i))) {
System.out.print("Updating trait from " + tpm.getNodeValue(treeModel, treeModel.getNode(j)));
tpm.setNodeValue(treeModel, treeModel.getNode(j), tpm.getNodeValue(treeModel, treeModel.getNode(j)) + 1.0);
System.out.println(" to " + tpm.getNodeValue(treeModel, treeModel.getNode(j)));
}
}
}
}
/*if (tpm.getNodeValue(treeModel, treeModel.getNode(i)) == -1.0) {
for (int j = 0; j < treeModel.getNodeCount(); j++) {
if (treeModel.getNode(j) != treeModel.getNode(i)) {
if (tpm.getNodeValue(treeModel, treeModel.getNode(j)) >= tpm.getNodeValue(treeModel, treeModel.getNode(i))) {
System.out.print("Updating trait from " + tpm.getNodeValue(treeModel, treeModel.getNode(j)));
tpm.setNodeValue(treeModel, treeModel.getNode(j), tpm.getNodeValue(treeModel, treeModel.getNode(j)) + 1.0);
System.out.println(" to " + tpm.getNodeValue(treeModel, treeModel.getNode(j)));
}
}
}
}*/
}
System.out.println("Number of interpolations: " + numberOfInterpolations);
}
System.out.println("Done.\n");
}
/**
* Add the remaining taxa, which can be identified through the TreeDataLikelihood XML elements.
*/
public ArrayList<NodeRef> incorporateAdditionalTaxa(CheckPointUpdaterApp.UpdateChoice choice, BranchRates rateModel) {
System.out.println("Tree before adding taxa:\n" + treeModel.toString() + "\n");
ArrayList<NodeRef> newTaxaNodes = new ArrayList<NodeRef>();
for (String str : newTaxaNames) {
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
if (treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId().equals(str)) {
newTaxaNodes.add(treeModel.getExternalNode(i));
//always take into account Taxon dates vs. dates set through a TreeModel
System.out.println(treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId() + " with height "
+ treeModel.getNodeHeight(treeModel.getExternalNode(i)) + " or " + treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getHeight());
}
}
}
System.out.println("newTaxaNodes length = " + newTaxaNodes.size());
ArrayList<Taxon> currentTaxa = new ArrayList<Taxon>();
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
boolean taxonFound = false;
for (String str : newTaxaNames) {
if (str.equals((treeModel.getNodeTaxon(treeModel.getExternalNode(i))).getId())) {
taxonFound = true;
}
}
if (!taxonFound) {
System.out.println("Adding " + treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId() + " to list of current taxa");
currentTaxa.add(treeModel.getNodeTaxon(treeModel.getExternalNode(i)));
}
}
System.out.println("Current taxa count = " + currentTaxa.size());
//iterate over both current taxa and to be added taxa
boolean originTaxon = true;
for (Taxon taxon : currentTaxa) {
if (taxon.getHeight() == 0.0) {
originTaxon = false;
System.out.println("Current taxon " + taxon.getId() + " has node height 0.0");
}
}
for (NodeRef newTaxon : newTaxaNodes) {
if (treeModel.getNodeTaxon(newTaxon).getHeight() == 0.0) {
originTaxon = false;
System.out.println("New taxon " + treeModel.getNodeTaxon(newTaxon).getId() + " has node height 0.0");
}
}
//check the Tree(Data)Likelihoods in the connected set of likelihoods
//focus on TreeDataLikelihood, which has getTree() to get the tree for each likelihood
//also get the DataLikelihoodDelegate from TreeDataLikelihood
ArrayList<TreeDataLikelihood> likelihoods = new ArrayList<TreeDataLikelihood>();
ArrayList<Tree> trees = new ArrayList<Tree>();
ArrayList<DataLikelihoodDelegate> delegates = new ArrayList<DataLikelihoodDelegate>();
for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
if (likelihood instanceof TreeDataLikelihood) {
likelihoods.add((TreeDataLikelihood)likelihood);
trees.add(((TreeDataLikelihood) likelihood).getTree());
delegates.add(((TreeDataLikelihood) likelihood).getDataLikelihoodDelegate());
}
}
//suggested to go through TreeDataLikelihoodParser and give it an extra option to create a HashMap
//keyed by the tree; am currently not overly fond of this approach
ArrayList<PatternList> patternLists = new ArrayList<PatternList>();
for (DataLikelihoodDelegate del : delegates) {
if (del instanceof BeagleDataLikelihoodDelegate) {
patternLists.add(((BeagleDataLikelihoodDelegate) del).getPatternList());
} else if (del instanceof MultiPartitionDataLikelihoodDelegate) {
MultiPartitionDataLikelihoodDelegate mpdld = (MultiPartitionDataLikelihoodDelegate)del;
List<PatternList> list = mpdld.getPatternLists();
for (PatternList pList : list) {
patternLists.add(pList);
}
}
}
if (patternLists.size() == 0) {
throw new RuntimeException("No patterns detected. Please make sure the XML file is BEAST 1.9 compatible.");
}
//aggregate all patterns to create distance matrix
//TODO What about different trees for different partitions?
Patterns patterns = new Patterns(patternLists.get(0));
if (patternLists.size() > 1) {
for (int i = 1; i < patternLists.size(); i++) {
patterns.addPatterns(patternLists.get(i));
}
}
//set the patterns for the distance matrix computations
choice.setPatterns(patterns);
//add new taxa one at a time
System.out.println("Adding " + newTaxaNodes.size() + " taxa ...");
for (NodeRef newTaxon : newTaxaNodes) {
treeModel.setNodeHeight(newTaxon, treeModel.getNodeTaxon(newTaxon).getHeight());
System.out.println("\nadding Taxon: " + newTaxon + " (height = " + treeModel.getNodeHeight(newTaxon) + ")");
//check if this taxon has a more recent sampling date than all other nodes in the current TreeModel
double offset = checkCurrentTreeNodes(newTaxon, treeModel.getRoot());
System.out.println("Sampling date offset when adding " + newTaxon + " = " + offset);
//if so, update all nodes current in the tree (i.e. recursively from the root)
//AND set its current node height to 0.0 IF no originTaxon has been found
if (offset < 0.0) {
if (!originTaxon) {
System.out.println("Updating all node heights with offset " + Math.abs(offset));
updateAllTreeNodes(Math.abs(offset), treeModel.getRoot());
treeModel.setNodeHeight(newTaxon, 0.0);
}
} else if (offset == 0.0) {
if (!originTaxon) {
treeModel.setNodeHeight(newTaxon, 0.0);
}
}
//get the closest Taxon to the Taxon that needs to be added
//take into account which taxa can currently be chosen
Taxon closest = choice.getClosestTaxon(treeModel.getNodeTaxon(newTaxon), currentTaxa);
System.out.println("\nclosest Taxon: " + closest + " with original height: " + closest.getHeight());
//get the distance between these two taxa
double distance = choice.getDistance(treeModel.getNodeTaxon(newTaxon), closest);
System.out.println("at distance: " + distance);
//TODO what if distance == 0.0 ??? how to choose closest taxon then (in absence of geo info)?
//find the NodeRef for the closest Taxon (do not rely on node numbering)
NodeRef closestRef = null;
//careful with node numbering and subtract number of new taxa
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
if (treeModel.getNodeTaxon(treeModel.getExternalNode(i)) == closest) {
closestRef = treeModel.getExternalNode(i);
}
}
System.out.println(closestRef + " with height " + treeModel.getNodeHeight(closestRef));
//System.out.println("trying to set node height: " + closestRef + " from " + treeModel.getNodeHeight(closestRef) + " to " + closest.getHeight());
//treeModel.setNodeHeight(closestRef, closest.getHeight());
double timeForDistance = distance/rateModel.getBranchRate(treeModel, closestRef);
System.out.println("timeForDistance = " + timeForDistance);
//get parent node of branch that will be split
NodeRef parent = treeModel.getParent(closestRef);
//determine height of new node
double insertHeight;
if (treeModel.getNodeHeight(closestRef) == treeModel.getNodeHeight(newTaxon)) {
insertHeight = treeModel.getNodeHeight(closestRef) + timeForDistance/2.0;
System.out.println("treeModel.getNodeHeight(closestRef) == treeModel.getNodeHeight(newTaxon): " + insertHeight);
if (insertHeight >= treeModel.getNodeHeight(parent)) {
insertHeight = treeModel.getNodeHeight(closestRef) + EPSILON*(treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(closestRef));
}
} else {
double remainder = (timeForDistance - Math.abs(treeModel.getNodeHeight(closestRef) - treeModel.getNodeHeight(newTaxon)))/2.0;
if (remainder > 0) {
insertHeight = Math.max(treeModel.getNodeHeight(closestRef),treeModel.getNodeHeight(newTaxon)) + remainder;
System.out.println("remainder > 0: " + insertHeight);
if (insertHeight >= treeModel.getNodeHeight(parent)) {
insertHeight = treeModel.getNodeHeight(closestRef) + EPSILON*(treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(closestRef));
}
} else {
insertHeight = EPSILON*(treeModel.getNodeHeight(parent) - Math.max(treeModel.getNodeHeight(closestRef),treeModel.getNodeHeight(newTaxon)));
insertHeight += Math.max(treeModel.getNodeHeight(closestRef),treeModel.getNodeHeight(newTaxon));
System.out.println("remainder <= 0: " + insertHeight);
}
}
System.out.println("insert at height: " + insertHeight);
//pass on all the necessary variables to a method that adds the new taxon to the tree
addTaxonAlongBranch(newTaxon, parent, closestRef, insertHeight);
//option to print tree after each taxon addition
System.out.println("\nTree after adding taxon " + newTaxon + ":\n" + treeModel.toString());
//add newly added Taxon to list of current taxa
currentTaxa.add(treeModel.getNodeTaxon(newTaxon));
}
//System.out.println(treeModel.toString());
return newTaxaNodes;
}
/**
* Add a given offset to all node height (both internal and external) of a tree
* @param offset The offset to add to the node height
* @param currentRoot Root of the tree
*/
private void updateAllTreeNodes(double offset, NodeRef currentRoot) {
treeModel.setNodeHeight(currentRoot, treeModel.getNodeHeight(currentRoot) + offset);
for (int i = 0; i < treeModel.getChildCount(currentRoot); i++) {
updateAllTreeNodes(offset, treeModel.getChild(currentRoot, i));
}
}
/**
* Check if the taxon to be added has a more recent sampling date than all external nodes currently in the tree.
* @param newTaxon The taxon to be added
* @param currentRoot The current connected tree that does not yet contain the @newTaxon taxon
* @return Offset of the node height of the new taxon versus the current most recent sampling date
*/
private double checkCurrentTreeNodes(NodeRef newTaxon, NodeRef currentRoot) {
/*System.out.println(currentRoot);
if (treeModel.getChildCount(currentRoot) == 0) {
System.out.println("root date = " + treeModel.getNodeTaxon(currentRoot).getDate().getTimeValue());
}*/
if (treeModel.getChildCount(currentRoot) == 0) {
return treeModel.getNodeTaxon(currentRoot).getDate().getTimeValue() - treeModel.getNodeTaxon(newTaxon).getDate().getTimeValue();
} else {
double maximum = -Double.MAX_VALUE;
for (int i = 0; i < treeModel.getChildCount(currentRoot); i++) {
maximum = Math.max(checkCurrentTreeNodes(newTaxon, treeModel.getChild(currentRoot, i)), maximum);
}
return maximum;
}
}
/**
* Adds a taxon along a branch specified by its parent and child node, at a specified height
* @param newTaxon The new Taxon to be added to the tree
* @param parentNode The parent node of the branch along which the new taxon is to be added
* @param childNode The child of the branch along which the new taxon is to be added
* @param insertHeight The height of the new internal node that will be created
*/
private void addTaxonAlongBranch(NodeRef newTaxon, NodeRef parentNode, NodeRef childNode, double insertHeight) {
treeModel.beginTreeEdit();
//remove child node that correspondes to childNode argument
treeModel.removeChild(parentNode, childNode);
//add a currently unused internal node as the new child node
NodeRef internalNode = null;
for (int i = 0; i < treeModel.getInternalNodeCount(); i++) {
if (treeModel.getChildCount(treeModel.getInternalNode(i)) == 0 && treeModel.getParent(treeModel.getInternalNode(i)) == null) {
internalNode = treeModel.getInternalNode(i);
System.out.println("\ninternal node found: " + internalNode.getNumber());
break;
}
}
if (internalNode == null) {
throw new RuntimeException("No free internal node found for adding a new taxon.");
}
//add internal node as a child of the old parent node
treeModel.addChild(parentNode, internalNode);
//add the old child node as a child of the new internal node
treeModel.addChild(internalNode, childNode);
//add the new taxon as a child of the new internal node
treeModel.addChild(internalNode, newTaxon);
//still need to set the height of the new internal node
treeModel.setNodeHeight(internalNode, insertHeight);
System.out.println("\nparent node (" + parentNode + ") height: " + treeModel.getNodeHeight(parentNode));
System.out.println("child node (" + childNode + ") height: " + treeModel.getNodeHeight(childNode));
System.out.println("internal node (" + internalNode + ") height: " + treeModel.getNodeHeight(internalNode));
treeModel.endTreeEdit();
}
/**
* Check whether all the old taxa are still present in the new analysis. Also check whether the
* additional taxa have been put at the end of the taxa list.
* @param taxaNames The taxa names (and order) from the old XML, retrieved from the checkpoint file
* @return An ArrayList containing the names of the additional taxa.
*/
private boolean checkTaxaOrder(String[] taxaNames) {
int external = treeModel.getExternalNodeCount();
newTaxaNames = new ArrayList<String>();
for (int i = 0; i < external; i++) {
int j = 0;
boolean taxonFound = false;
while (!taxonFound) {
if (treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId().equals(taxaNames[j])) {
taxonFound = true;
} else {
j++;
if (j >= taxaNames.length) {
newTaxaNames.add(treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId());
taxonFound = true;
}
}
}
}
System.out.println();
for (String str : newTaxaNames) {
System.out.println("New taxon found: " + str);
}
System.out.println();
//With added taxa the order of the external nodes changes
//Aim here is to build a starting tree containing only the taxa from the previous analysis.
for (int i = 0; i < taxaNames.length; i++) {
if (!taxaNames[i].equals(treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId())) {
String error = taxaNames[i] + " vs. " + treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId();
System.out.println("Taxa listed in the wrong order; append new taxa at the end:\n" + error);
//throw new RuntimeException("Taxa listed in the wrong order; append new taxa at the end:\n" + error);
return false;
} else {
System.out.println(taxaNames[i] + " vs. " + treeModel.getNodeTaxon(treeModel.getExternalNode(i)).getId());
}
}
return true;
}
private void createNodeMap(String[] taxaNames) {
System.out.println("Creating a node mapping:");
int external = treeModel.getExternalNodeCount();
nodeMap = new int[external];
for (int i = 0; i < taxaNames.length; i++) {
for (int j = 0; j < external; j++) {
if (taxaNames[i].equals(treeModel.getNodeTaxon(treeModel.getExternalNode(j)).getId())) {
//taxon found
nodeMap[i] = j;
}
}
}
}
} |
package org.diorite.impl.pipelines.event.player;
import java.util.Collection;
import java.util.Objects;
import java.util.UUID;
import org.diorite.impl.connection.packets.play.out.PacketPlayOutTransaction;
import org.diorite.impl.entity.EntityImpl;
import org.diorite.impl.entity.ItemImpl;
import org.diorite.impl.entity.PlayerImpl;
import org.diorite.impl.inventory.PlayerInventoryImpl;
import org.diorite.impl.inventory.item.ItemStackImpl;
import org.diorite.GameMode;
import org.diorite.event.pipelines.event.player.InventoryClickPipeline;
import org.diorite.event.player.PlayerInventoryClickEvent;
import org.diorite.inventory.ClickType;
import org.diorite.inventory.item.ItemStack;
import org.diorite.inventory.item.BaseItemStack;
import org.diorite.utils.pipeline.SimpleEventPipeline;
public class InventoryClickPipelineImpl extends SimpleEventPipeline<PlayerInventoryClickEvent> implements InventoryClickPipeline
{
private static final int HOTBAR_BEGIN_ID = 36;
@Override
public void reset_()
{
this.addLast("Diorite|Handle", (evt, pipeline) -> {
if (evt.isCancelled())
{
((PlayerImpl) evt.getPlayer()).getNetworkManager().sendPacket(new PacketPlayOutTransaction(evt.getWindowId(), evt.getActionNumber(), false));
return;
}
System.out.println(evt.toString());
final boolean accepted = this.handleClick(evt);
((PlayerImpl) evt.getPlayer()).getNetworkManager().sendPacket(new PacketPlayOutTransaction(evt.getWindowId(), evt.getActionNumber(), accepted));
if (! accepted)
{
System.out.println("Rejected inventory click action from player " + evt.getPlayer().getName());
}
});
}
protected boolean handleClick(final PlayerInventoryClickEvent e)
{
final PlayerImpl player = (PlayerImpl) e.getPlayer();
final ClickType ct = e.getClickType();
final ItemStackImpl cursor = ItemStackImpl.wrap(e.getCursorItem());
final int slot = e.getClickedSlot();
final PlayerInventoryImpl inv = player.getInventory(); // TODO
final ItemStackImpl clicked = ItemStackImpl.wrap(e.getClickedItem());
if (Objects.equals(ct, ClickType.MOUSE_LEFT))
{
if (cursor == null)
{
if ((clicked != null) && (! inv.atomicReplace(slot, clicked, null) || ! inv.atomicReplaceCursorItem(null, clicked)))
{
return false; // item changed before we made own change
}
}
else
{
if (cursor.isSimilar(clicked))
{
final ItemStack newCursor = clicked.combine(cursor);
if (! inv.atomicReplaceCursorItem(cursor, newCursor))
{
return false;
}
}
else
{
if (slot == 0) // result slot, TODO: slot type, finish for other clicks
{
return true;
}
if (! inv.atomicReplace(slot, clicked, cursor) || ! inv.atomicReplaceCursorItem(cursor, clicked))
{
return false; // item changed before we made own change
}
}
}
}
else if (Objects.equals(ct, ClickType.MOUSE_RIGHT))
{
if (cursor == null)
{
if (clicked == null)
{
return true;
}
final ItemStack splitted;
if (clicked.getAmount() == 1)
{
splitted = clicked;
if (! inv.atomicReplace(slot, clicked, null))
{
return false;
}
}
else
{
splitted = clicked.split(this.getAmountToStayInHand(clicked.getAmount()));
}
if (! inv.atomicReplaceCursorItem(null, (splitted != null) ? splitted : clicked))
{
return false;
}
}
else // cursor != null
{
if (clicked == null)
{
final ItemStack splitted = cursor.split(1);
if (! inv.atomicReplace(slot, null, (splitted == null) ? cursor : splitted))
{
return false;
}
}
else
{
if (clicked.isSimilar(cursor))
{
if (! inv.atomicReplaceCursorItem(cursor, clicked.combine(cursor)))
{
return false;
}
}
else
{
if (! inv.atomicReplace(slot, clicked, cursor) || ! inv.atomicReplaceCursorItem(cursor, clicked))
{
return false;
}
}
}
} // end cursor != null
} // end MOUSE_RIGHT
else if (Objects.equals(ct, ClickType.SHIFT_MOUSE_LEFT) || Objects.equals(ct, ClickType.SHIFT_MOUSE_RIGHT))
{
if (clicked == null)
{
return true;
}
// FIXME zbroja wskakuje na pola od armoru - tylko jesli sa wolne
// TODO dopracowac to bo ledwo dziala
if (slot >= HOTBAR_BEGIN_ID)
{
// clicked on hotbar
if (! inv.atomicReplace(slot, clicked, null))
{
return false;
}
inv.getFullEqInventory().add(clicked);
}
else
{
// clicked on other slot
if (! inv.atomicReplace(slot, clicked, null))
{
return false;
}
inv.getHotbarInventory().add(clicked);
}
}
else if (Objects.equals(ct, ClickType.DROP_KEY))
{
if (clicked.getAmount() == 1)
{
if (! inv.atomicReplace(slot, clicked, null))
{
return false;
}
// TODO wywalic itemek na ziemie
}
else
{
final ItemStack toDrop = clicked.split(1);
// TODO wywalic itemek toDrop na ziemie
}
}
else if (Objects.equals(ct, ClickType.CTRL_DROP_KEY))
{
if (! inv.atomicReplace(slot, clicked, null))
{
return false;
}
// TODO Gdy juz beda entities to wywalic itemek na ziemie. Aktualnie po prostu znika
}
else if (ct.getMode() == 2) // 2 -> hot bar action
{
if ((ct.getButton() < 0) || (ct.getButton() > 8))
{
return false;
}
final ItemStack inHeldSlot = inv.getHotbarInventory().getItem(ct.getButton());
return inv.atomicReplace(slot, clicked, inHeldSlot) && inv.getHotbarInventory().atomicReplace(ct.getButton(), inHeldSlot, clicked);
}
else if (Objects.equals(ct, ClickType.MOUSE_LEFT_OUTSIDE))
{
if ((cursor == null) || (cursor.getAmount() <= 0))
{
inv.setCursorItem(null);
return true;
}
if (! inv.atomicReplaceCursorItem(cursor, null))
{
return false;
}
final ItemImpl item = new ItemImpl(UUID.randomUUID(), player.getServer(), EntityImpl.getNextEntityID(), player.getLocation().addX(2)); // TODO:velocity + some .spawnEntity method
item.setItemStack(new BaseItemStack(cursor.getMaterial(), cursor.getAmount()));
player.getWorld().addEntity(item);
return true;
}
else if (Objects.equals(ct, ClickType.MOUSE_RIGHT_OUTSIDE))
{
if ((cursor == null) || (cursor.getAmount() <= 0))
{
inv.setCursorItem(null);
return true;
}
final ItemImpl item = new ItemImpl(UUID.randomUUID(), player.getServer(), EntityImpl.getNextEntityID(), player.getLocation().addX(2)); // TODO:velocity + some .spawnEntity method
item.setItemStack(new BaseItemStack(cursor.getMaterial(), 1));
if (cursor.getAmount() == 1)
{
if (! inv.atomicReplaceCursorItem(cursor, null))
{
return false;
}
player.getWorld().addEntity(item);
return true;
}
cursor.setAmount(cursor.getAmount() - 1);
player.getWorld().addEntity(item);
return true;
}
else if (Objects.equals(ct, ClickType.MOUSE_MIDDLE))
{
if (! Objects.equals(player.getGameMode(), GameMode.CREATIVE))
{
return true; // true? false?
}
if ((cursor != null) && (clicked != null))
{
return true;
}
final ItemStack newCursor = new BaseItemStack(clicked);
newCursor.setAmount(newCursor.getMaterial().getMaxStack());
return inv.atomicReplaceCursorItem(null, newCursor);
}
else if (Objects.equals(ct, ClickType.MOUSE_LEFT_DRAG_START) || Objects.equals(ct, ClickType.MOUSE_RIGHT_DRAG_START))
{
return inv.getDragController().start(ct.getButton() == ClickType.MOUSE_RIGHT_DRAG_START.getButton());
}
else if (Objects.equals(ct, ClickType.MOUSE_LEFT_DRAG_ADD) || Objects.equals(ct, ClickType.MOUSE_RIGHT_DRAG_ADD))
{
return inv.getDragController().addSlot(ct.getButton() == ClickType.MOUSE_RIGHT_DRAG_ADD.getButton(), slot);
}
else if (Objects.equals(ct, ClickType.MOUSE_LEFT_DRAG_END) || Objects.equals(ct, ClickType.MOUSE_RIGHT_DRAG_END))
{
final boolean isRightClick = ct.getButton() == ClickType.MOUSE_RIGHT_DRAG_END.getButton();
final Collection<Integer> result = inv.getDragController().end(isRightClick);
if ((cursor == null) || (result == null))
{
return false;
}
ItemStack newCursor = new BaseItemStack(cursor);
final int perSlot = isRightClick ? 1 : (cursor.getAmount() / result.size());
for (final int dragSlot : result)
{
final ItemStackImpl oldItem = inv.getItem(dragSlot);
if ((oldItem == null) || cursor.isSimilar(oldItem))
{
final ItemStack itemStackToCombine = new BaseItemStack(cursor);
itemStackToCombine.setAmount(perSlot);
final int combined;
if (oldItem != null)
{
final ItemStackImpl uncomb = oldItem.combine(itemStackToCombine);
combined = perSlot - ((uncomb == null) ? 0 : uncomb.getAmount());
}
else
{
combined = perSlot;
inv.setItem(dragSlot, new BaseItemStack(newCursor.getMaterial(), combined)); // FIXME item lose metadata
}
newCursor.setAmount(newCursor.getAmount() - combined);
if (newCursor.getAmount() == 0)
{
newCursor = null;
break;
}
}
}
return inv.atomicReplaceCursorItem(cursor, newCursor);
}
else if (Objects.equals(ct, ClickType.DOUBLE_CLICK))
{
if (cursor == null)
{
return true;
}
final int slots = 44;
for (int i = 0; (i < slots) && (cursor.getAmount() < cursor.getMaterial().getMaxStack()); i++)
{
final ItemStack item = inv.getItem(i);
if ((item == null) || ! cursor.isSimilar(item) /* || slot type == RESULT */)
{
continue;
}
final int newCursor = cursor.getAmount() +Math.min(item.getAmount(), cursor.getMaterial().getMaxStack() - cursor.getAmount());
final int newItem = item.getAmount() - newCursor;
cursor.setAmount(newCursor);
if (newItem <= 0)
{
if (! inv.atomicReplace(i, item, null))
{
return false;
}
}
else
{
item.setAmount(newItem);
}
}
}
// TODO remember about throwing item on cursor to ground when closing eq
else
{
return false; // Action not supported
}
return true;
}
protected int getAmountToStayInHand(final int amount)
{
return ((amount % 2) == 0) ? (amount / 2) : ((amount / 2) + 1);
}
} |
package com.techhounds.subsystems;
import com.techhounds.RobotMap;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class DriveSubsystem{
// TODO: Add Encoders
// TODO: Add Implementation for Set Drive Power (maybe Voltage?)
// TODO: Add Drive Distance PID Controller
// TODO: Add Gyro Turn PID Controller
private Spark left;
private Spark right;
private boolean rotating;
private PIDController pid;
private final double driver_p;
private final double driver_i;
private final double driver_d;
private final double gyro_p;
private final double gyro_i;
private final double gyro_d;
private static DriveSubsystem instance;
private DriveSubsystem() {
left = new Spark(RobotMap.DriveTrain.DRIVE_LEFT_MOTOR);
left.setInverted(RobotMap.DriveTrain.DRIVE_LEFT_IS_INVERTED);
right = new Spark(RobotMap.DriveTrain.DRIVE_RIGHT_MOTOR);
right.setInverted(RobotMap.DriveTrain.DRIVE_RIGHT_IS_INVERTED);
driver_p = 0.0001;
driver_i = 0;
driver_d = 0;
gyro_p = 0.0001;
gyro_i = 0;
gyro_d = 0;
}
public static DriveSubsystem getInstance() {
if(instance == null)
instance = new DriveSubsystem();
return instance;
}
public void loadStraightPIDValues(double p, double i, double d) {
rotating = false;
pid = new PIDController(p, i, d,
new PIDSource() {
@Override
public void setPIDSourceType(PIDSourceType pidSource) {
// TODO Auto-generated method stub
}
@Override
public double pidGet() {
// TODO Auto-generated method stub
return getLeftSpeed();
}
@Override
public PIDSourceType getPIDSourceType() {
// TODO Auto-generated method stub
return PIDSourceType.kDisplacement;
};
},
new PIDOutput() {
@Override
public void pidWrite(double output) {
setBothSpeed(output);
}
});
enablePID();
}
public void enablePID() {
if(pid != null) {
pid.enable();
}
}
public void disablePID() {
if(pid != null) {
pid.disable();
}
}
public void loadGyroPIDValues(double p, double i, double d) {
rotating = true;
pid = new PIDController(p, i, d,
new PIDSource() {
@Override
public void setPIDSourceType(PIDSourceType pidSource) {
}
@Override
public double pidGet() {
return GyroSubsystem.getInstance().getRotation();
}
@Override
public PIDSourceType getPIDSourceType() {
// TODO Auto-generated method stub
return PIDSourceType.kDisplacement;
};
},
new PIDOutput() {
@Override
public void pidWrite(double output) {
setBothSpeed(output);
}
});
enablePID();
}
public void setLeftSpeed(double speed) {
left.set(speed);
}
public void setRightSpeed(double speed) {
right.set(speed);
}
public void setBothSpeed(double output) {
left.set(output);
if(rotating) right.set(-output);
else right.set(output);
}
public double getLeftSpeed() {
return left.get();
}
public double getRightSpeed() {
return right.get();
}
public double getPIDError() {
return pid.getError();
}
public void updateSmartDashboard() {
SmartDashboard.putNumber("Driver Left Speed", getLeftSpeed());
SmartDashboard.putNumber("Driver Right Speed", getRightSpeed());
SmartDashboard.putNumber("Driver PID Error", getPIDError());
}
protected void initDefaultCommand() {
// TODO: Add Default command for DriveWithGamepad()
}
} |
package dr.evomodel.operators;
import dr.evolution.tree.MutableTree;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.OperatorFailedException;
import dr.math.MathUtils;
import dr.xml.*;
/**
* Implements branch exchange operations. There is a NARROW and WIDE variety.
* The narrow exchange is very similar to a rooted-tree nearest-neighbour
* interchange but with the restriction that node height must remain consistent.
* <p/>
* KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips!
*/
public class ExchangeOperator extends AbstractTreeOperator {
public static final String NARROW_EXCHANGE = "narrowExchange";
public static final String WIDE_EXCHANGE = "wideExchange";
public static final String INTERMEDIATE_EXCHANGE = "intermediateExchange";
public static final int NARROW = 0;
public static final int WIDE = 1;
public static final int INTERMEDIATE = 2;
private static final int MAX_TRIES = 100;
private int mode = NARROW;
private TreeModel tree;
private double[] distances;
public ExchangeOperator(int mode, TreeModel tree, double weight) {
this.mode = mode;
this.tree = tree;
setWeight(weight);
}
public double doOperation() throws OperatorFailedException {
int tipCount = tree.getExternalNodeCount();
double hastingsRatio = 0;
switch (mode) {
case NARROW:
narrow();
break;
case WIDE:
wide();
break;
case INTERMEDIATE:
hastingsRatio = intermediate();
break;
}
if (tree.getExternalNodeCount() != tipCount) {
throw new RuntimeException("Lost some tips in "
+ ((mode == NARROW) ? "NARROW mode." : "WIDE mode."));
}
return hastingsRatio;
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void narrow() throws OperatorFailedException {
final int nNodes = tree.getNodeCount();
final NodeRef root = tree.getRoot();
NodeRef i = tree.getNode(MathUtils.nextInt(nNodes));
while (root == i || tree.getParent(i) == root) {
i = tree.getNode(MathUtils.nextInt(nNodes));
}
final NodeRef iParent = tree.getParent(i);
final NodeRef iGrandParent = tree.getParent(iParent);
NodeRef iUncle = tree.getChild(iGrandParent, 0);
if (iUncle == iParent) {
iUncle = tree.getChild(iGrandParent, 1);
}
assert tree.getNodeHeight(i) < tree.getNodeHeight(iGrandParent);
if (tree.getNodeHeight(iUncle) < tree.getNodeHeight(iParent)) {
eupdate(i, iUncle, iParent, iGrandParent);
tree.pushTreeChangedEvent(iParent);
tree.pushTreeChangedEvent(iGrandParent);
return;
}
// System.out.println("tries = " + tries);
throw new OperatorFailedException(
"Couldn't find valid narrow move on this tree!!");
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void wide() throws OperatorFailedException {
final int nodeCount = tree.getNodeCount();
final NodeRef root = tree.getRoot();
NodeRef i = root;
while (root == i) {
i = tree.getNode(MathUtils.nextInt(nodeCount));
}
NodeRef j = i; // tree.getNode(MathUtils.nextInt(nodeCount));
while (j == i || j == root) {
j = tree.getNode(MathUtils.nextInt(nodeCount));
}
final NodeRef iP = tree.getParent(i);
final NodeRef jP = tree.getParent(j);
if ((iP != jP) && (i != jP) && (j != iP)
&& (tree.getNodeHeight(j) < tree.getNodeHeight(iP))
&& (tree.getNodeHeight(i) < tree.getNodeHeight(jP))) {
eupdate(i, j, iP, jP);
// System.out.println("tries = " + tries+1);
return;
}
throw new OperatorFailedException(
"Couldn't find valid wide move on this tree!");
}
/**
* @deprecated
* WARNING: SHOULD NOT BE USED!
* WARNING: Assumes strictly bifurcating tree.
*/
public double intermediate() throws OperatorFailedException {
final int nodeCount = tree.getNodeCount();
final NodeRef root = tree.getRoot();
for (int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i, j;
NodeRef[] possibleNodes;
do {
// get a random node
i = root; // tree.getNode(MathUtils.nextInt(nodeCount));
// if (root != i) {
// possibleNodes = tree.getNodes();
// check if we got the root
while (root == i) {
// if so get another one till we haven't got anymore the
// root
i = tree.getNode(MathUtils.nextInt(nodeCount));
// if (root != i) {
// possibleNodes = tree.getNodes();
}
possibleNodes = tree.getNodes();
// get another random node
// NodeRef j = tree.getNode(MathUtils.nextInt(nodeCount));
j = getRandomNode(possibleNodes, i);
// check if they are the same and if the new node is the root
} while (j == null || j == i || j == root);
double forward = getWinningChance(indexOf(possibleNodes, j));
// possibleNodes = getPossibleNodes(j);
calcDistances(possibleNodes, j);
forward += getWinningChance(indexOf(possibleNodes, i));
// get the parent of both of them
final NodeRef iP = tree.getParent(i);
final NodeRef jP = tree.getParent(j);
// check if both parents are equal -> we are siblings :) (this
// wouldnt effect a change on topology)
// check if I m your parent or vice versa (this would destroy the
// tree)
// check if you are younger then my father
// check if I m younger then your father
if ((iP != jP) && (i != jP) && (j != iP)
&& (tree.getNodeHeight(j) < tree.getNodeHeight(iP))
&& (tree.getNodeHeight(i) < tree.getNodeHeight(jP))) {
// if 1 & 2 are false and 3 & 4 are true then we found a valid
// candidate
exchangeNodes(tree, i, j, iP, jP);
// possibleNodes = getPossibleNodes(i);
calcDistances(possibleNodes, i);
double backward = getWinningChance(indexOf(possibleNodes, j));
// possibleNodes = getPossibleNodes(j);
calcDistances(possibleNodes, j);
backward += getWinningChance(indexOf(possibleNodes, i));
// System.out.println("tries = " + tries+1);
return Math.log(Math.min(1, (backward) / (forward)));
// return 0.0;
}
}
throw new OperatorFailedException(
"Couldn't find valid wide move on this tree!");
}
/* why not use Arrays.asList(a).indexOf(n) ? */
private int indexOf(NodeRef[] a, NodeRef n) {
for (int i = 0; i < a.length; i++) {
if (a[i] == n) {
return i;
}
}
return -1;
}
private double getWinningChance(int index) {
double sum = 0;
for (int i = 0; i < distances.length; i++) {
sum += (1.0 / distances[i]);
}
return (1.0 / distances[index]) / sum;
}
private void calcDistances(NodeRef[] nodes, NodeRef ref) {
distances = new double[nodes.length];
for (int i = 0; i < nodes.length; i++) {
distances[i] = getNodeDistance(ref, nodes[i]) + 1;
}
}
private NodeRef getRandomNode(NodeRef[] nodes, NodeRef ref) {
calcDistances(nodes, ref);
double sum = 0;
for (int i = 0; i < distances.length; i++) {
sum += 1.0 / distances[i];
}
double randomValue = MathUtils.nextDouble() * sum;
NodeRef n = null;
for (int i = 0; i < distances.length; i++) {
randomValue -= 1.0 / distances[i];
if (randomValue <= 0) {
n = nodes[i];
break;
}
}
return n;
}
private int getNodeDistance(NodeRef i, NodeRef j) {
int count = 0;
while (i != j) {
count++;
if (tree.getNodeHeight(i) < tree.getNodeHeight(j)) {
i = tree.getParent(i);
} else {
j = tree.getParent(j);
}
}
return count;
}
public int getMode() {
return mode;
}
public String getOperatorName() {
return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange" + "("
+ tree.getId() + ")";
}
/* exchange subtrees whose root are i and j */
private void eupdate(NodeRef i, NodeRef j, NodeRef iP, NodeRef jP)
throws OperatorFailedException {
tree.beginTreeEdit();
tree.removeChild(iP, i);
tree.removeChild(jP, j);
tree.addChild(jP, i);
tree.addChild(iP, j);
try {
tree.endTreeEdit();
} catch (MutableTree.InvalidTreeException ite) {
throw new OperatorFailedException(ite.toString());
}
}
public double getMinimumAcceptanceLevel() {
if (mode == NARROW)
return 0.05;
else
return 0.01;
}
public double getMinimumGoodAcceptanceLevel() {
if (mode == NARROW)
return 0.05;
else
return 0.01;
}
public String getPerformanceSuggestion() {
if (MCMCOperator.Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (MCMCOperator.Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
return "";
} else {
return "";
}
}
public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NARROW_EXCHANGE;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
final double weight = xo.getDoubleAttribute("weight");
return new ExchangeOperator(NARROW, treeModel, weight);
}
// AbstractXMLObjectParser implementation
public String getParserDescription() {
return "This element represents a narrow exchange operator. "
+ "This operator swaps a random subtree with its uncle.";
}
public Class getReturnType() {
return ExchangeOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
AttributeRule.newDoubleRule("weight"),
new ElementRule(TreeModel.class) };
};
public static XMLObjectParser WIDE_EXCHANGE_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return WIDE_EXCHANGE;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
double weight = xo.getDoubleAttribute("weight");
return new ExchangeOperator(WIDE, treeModel, weight);
}
// AbstractXMLObjectParser implementation
public String getParserDescription() {
return "This element represents a wide exchange operator. "
+ "This operator swaps two random subtrees.";
}
public Class getReturnType() {
return ExchangeOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
AttributeRule.newDoubleRule("weight"),
new ElementRule(TreeModel.class) };
};
public static XMLObjectParser INTERMEDIATE_EXCHANGE_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return INTERMEDIATE_EXCHANGE;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
double weight = xo.getDoubleAttribute("weight");
return new ExchangeOperator(INTERMEDIATE, treeModel, weight);
}
// AbstractXMLObjectParser implementation
public String getParserDescription() {
return "This element represents a intermediate exchange operator. "
+ "This operator swaps two random subtrees.";
}
public Class getReturnType() {
return ExchangeOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
AttributeRule.newDoubleRule("weight"),
new ElementRule(TreeModel.class) };
};
} |
package codeine.jsons.project;
import java.util.List;
import java.util.Map;
import codeine.api.NodeInfo;
import codeine.configuration.NodeMonitor;
import codeine.jsons.collectors.CollectorInfo;
import codeine.jsons.command.CommandInfo;
import codeine.jsons.nodes.NodeDiscoveryStrategy;
import codeine.permissions.UserProjectPermissions;
import codeine.utils.os.OperatingSystem;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class ProjectJson
{
private String name;
private String description;
private List<NodeMonitor> monitors = Lists.newArrayList();
private List<CollectorInfo> collectors = Lists.newArrayList();
private List<MailPolicyJson> mail = Lists.newArrayList();
private NodeDiscoveryStrategy node_discovery_startegy = NodeDiscoveryStrategy.Configuration;
private List<CommandInfo> commands = Lists.newArrayList();
private List<UserProjectPermissions> permissions = Lists.newArrayList();
private String nodes_discovery_script;
private String tags_discovery_script;
private String version_detection_script;
private List<NodeInfo> nodes_info = Lists.newArrayList();
private OperatingSystem operating_system = OperatingSystem.Linux;
private DiscardOldCommandsJson discard_old_commands = new DiscardOldCommandsJson(1000, null);
private List<EnvironmentVariable> environment_variables = Lists.newArrayList();
private List<String> include_project_commands = Lists.newArrayList();
public ProjectJson(String name) {
this.name = name;
}
public ProjectJson() {
}
public NodeMonitor getMonitor(String name)
{
for (NodeMonitor c : monitors)
{
if (c.name().equals(name))
{
return c;
}
}
return null;
}
@Override
public String toString() {
return "ProjectJson [" + (name != null ? "name=" + name + ", " : "")
+ (description != null ? "description=" + description : "") + "]";
}
public List<NodeMonitor> monitors() {
return monitors;
}
public List<MailPolicyJson> mail() {
return mail;
}
public NodeDiscoveryStrategy node_discovery_startegy() {
return node_discovery_startegy;
}
public void node_discovery_startegy(NodeDiscoveryStrategy newStrategy)
{
node_discovery_startegy = newStrategy;
}
public String name() {
return name;
}
public List<CommandInfo> commands() {
return commands;
}
public CommandInfo getCommand(String command) {
for (CommandInfo commandJson2 : commands()) {
if (commandJson2.name().equals(command)){
return commandJson2;
}
}
if (command.equals("switch-version")){
return new CommandInfo();
}
throw new IllegalArgumentException("command " + command + " not found in project " + name());
}
public void nodes_discovery_script(String content) {
this.nodes_discovery_script = content;
}
public void version_detection_script(String content) {
this.version_detection_script = content;
}
public String version_detection_script() {
return version_detection_script;
}
public void nodes_info(List<NodeInfo> nodes) {
this.nodes_info = nodes;
}
public void name(String name) {
this.name = name;
}
public String nodes_discovery_script() {
return nodes_discovery_script;
}
public List<NodeInfo> nodes_info() {
return nodes_info;
}
public String tags_discovery_script() {
return tags_discovery_script;
}
public List<UserProjectPermissions> permissions() {
return permissions;
}
public DiscardOldCommandsJson discard_old_commands() {
return discard_old_commands;
}
public OperatingSystem operating_system() {
return operating_system == null ? OperatingSystem.Linux : operating_system;
}
public Map<String, String> environmentVariables() {
Map<String, String> $ = Maps.newLinkedHashMap();
for (EnvironmentVariable environmentVariable : environment_variables) {
$.put(environmentVariable.key(), environmentVariable.value());
}
return $;
}
public List<CollectorInfo> collectors() {
return collectors;
}
public List<String> include_project_commands() {
return include_project_commands;
}
public String description() {
return description;
}
} |
package dr.inference.trace;
import dr.inferencexml.trace.MarginalLikelihoodAnalysisParser;
import dr.util.*;
import dr.xml.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Philippe Lemey
* @author Marc A. Suchard
*/
public class DnDsPerSiteAnalysis implements Citable {
public static final String DNDS_PER_SITE_ANALYSIS = "dNdSPerSiteAnalysis";
public static final String CUTOFF = "cutoff";
public static final String INCLUDE_SIGNIFICANT_SYMBOL = "includeSymbol";
public static final String INCLUDE_SIGNIFICANCE_LEVEL = "includeLevel";
public static final String INCLUDE_SITE_CLASSIFICATION = "includeClassification";
public static final String SIGNIFICANCE_TEST = "test";
public static final String SEPARATOR_STRING = "separator";
public DnDsPerSiteAnalysis(TraceList traceList) {
this.traceList = traceList;
this.numSites = traceList.getTraceCount();
this.format = new OutputFormat();
fieldWidth = 14;
firstField = 10;
numberFormatter = new NumberFormatter(6);
numberFormatter.setPadding(true);
numberFormatter.setFieldWidth(fieldWidth);
}
public void setIncludeMean(boolean b) {
format.includeMean = b;
}
public void setIncludeHPD(boolean b) {
format.includeHPD = b;
}
public void setIncludeSignificanceLevel(boolean b) {
format.includeSignificanceLevel = b;
}
public void setIncludeSignificantSymbol(boolean b) {
format.includeSignificantSymbol = b;
}
public void setIncludeSiteClassification(boolean b) {
format.includeSiteClassification = b;
}
public void setCutoff(double d) {
format.cutoff = d;
}
public void setSeparator(String s) {
format.separator = s;
}
public void setSignificanceTest(SignificanceTest t) {
format.test = t;
}
private String toStringSite(int index, OutputFormat format) {
StringBuilder sb = new StringBuilder();
traceList.analyseTrace(index);
TraceDistribution distribution = traceList.getDistributionStatistics(index);
sb.append(numberFormatter.formatToFieldWidth(Integer.toString(index + 1), firstField));
if (format.includeMean) {
sb.append(format.separator);
sb.append(numberFormatter.format(distribution.getMean()));
}
if (format.includeHPD) {
sb.append(format.separator);
sb.append(numberFormatter.format(distribution.getLowerHPD()));
sb.append(format.separator);
sb.append(numberFormatter.format(distribution.getUpperHPD()));
}
if (format.includeSignificanceLevel || format.includeSignificantSymbol || format.includeSiteClassification) {
boolean isSignificant = false;
String classification = "N";
String level;
if (format.test == SignificanceTest.NOT_EQUAL) {
double lower = distribution.getLowerHPD();
double upper = distribution.getUpperHPD();
// if ((lower < format.cutoff && upper < format.cutoff) ||
// (lower > format.cutoff && upper > format.cutoff)) {
if (lower < format.cutoff && upper < format.cutoff) {
level = numberFormatter.formatToFieldWidth(">0.95", fieldWidth);
isSignificant = true;
classification = "-";
} else if (lower > format.cutoff && upper > format.cutoff) {
level = numberFormatter.formatToFieldWidth(">0.95", fieldWidth);
isSignificant = true;
classification = "+";
} else {
level = numberFormatter.formatToFieldWidth("<=0.95", fieldWidth);
}
} else {
Object[] values = distribution.getValues();
double levelPosValue = 0.0;
double levelNegValue = 0.0;
int total = 0;
for (Object obj : values) {
double d = (Double) obj;
// if ((format.test == SignificanceTest.LESS_THAN && d < format.cutoff) ||
// (format.test == SignificanceTest.GREATER_THAN && d > format.cutoff)) {
if (format.test == SignificanceTest.LESS_THAN && d < format.cutoff) {
levelNegValue++;
} else if (format.test == SignificanceTest.GREATER_THAN && d > format.cutoff){
levelPosValue++;
}
total++;
}
levelPosValue /= total;
levelNegValue /= total;
if (levelPosValue > 0.95) {
isSignificant = true;
classification = "+";
} else if (levelNegValue > 0.95) {
isSignificant = true;
classification = "-";
}
if (levelPosValue > levelNegValue) {
level = numberFormatter.format(levelPosValue);
} else {
level = numberFormatter.format(levelNegValue);
}
}
if (format.includeSignificanceLevel) {
sb.append(format.separator);
sb.append(level);
}
if (format.includeSiteClassification) {
sb.append(format.separator);
sb.append(classification);
}
if (format.includeSignificantSymbol) {
sb.append(format.separator);
if (isSignificant) {
sb.append("*");
} else {
// Do nothing?
}
}
}
sb.append("\n");
return sb.toString();
}
public String header(OutputFormat format) {
StringBuilder sb = new StringBuilder();
sb.append("# Some information here\n");
sb.append("# Please cite: " + Citable.Utils.getCitationString(this));
sb.append(numberFormatter.formatToFieldWidth("Site", firstField));
if (format.includeMean) {
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Mean", fieldWidth));
}
if (format.includeHPD) {
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Lower", fieldWidth));
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Upper", fieldWidth));
}
if (format.includeSignificanceLevel) {
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Level", fieldWidth));
}
if (format.includeSiteClassification) {
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Classification", fieldWidth));
}
if (format.includeSignificantSymbol) {
sb.append(format.separator);
sb.append(numberFormatter.formatToFieldWidth("Significant", fieldWidth));
}
sb.append("\n");
return sb.toString();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(header(format));
for (int i = 0; i < numSites; ++i) {
sb.append(toStringSite(i, format));
}
return sb.toString();
}
public List<Citation> getCitations() {
List<Citation> citations = new ArrayList<Citation>();
citations.add(
new Citation(
new Author[]{
new Author("P", "Lemey"),
new Author("VN", "Minin"),
new Author("MA", "Suchard")
},
Citation.Status.IN_PREPARATION
)
);
return citations;
}
private class OutputFormat {
boolean includeMean;
boolean includeHPD;
boolean includeSignificanceLevel;
boolean includeSignificantSymbol;
boolean includeSiteClassification;
double cutoff;
SignificanceTest test;
String separator;
OutputFormat() {
this(true, true, true, true, true, 1.0, SignificanceTest.NOT_EQUAL, "\t");
}
OutputFormat(boolean includeMean,
boolean includeHPD,
boolean includeSignificanceLevel,
boolean includeSignificantSymbol,
boolean includeSiteClassification,
double cutoff,
SignificanceTest test,
String separator) {
this.includeMean = includeMean;
this.includeHPD = includeHPD;
this.includeSignificanceLevel = includeSignificanceLevel;
this.includeSignificantSymbol = includeSignificantSymbol;
this.cutoff = cutoff;
this.test = test;
this.separator = separator;
}
}
public enum SignificanceTest {
GREATER_THAN(">"),
LESS_THAN("<"),
NOT_EQUAL("!=");
private SignificanceTest(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static SignificanceTest parseFromString(String text) {
for (SignificanceTest test : SignificanceTest.values()) {
if (test.getText().compareToIgnoreCase(text) == 0)
return test;
}
return null;
}
private final String text;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return DNDS_PER_SITE_ANALYSIS;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String name = file.getName();
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, name);
fileName = file.getAbsolutePath();
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute(MarginalLikelihoodAnalysisParser.BURN_IN, maxState / 10);
//TODO: implement custom burn-in
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 5;
System.out.println("WARNING: Burn-in larger than total number of states - using to 20%");
}
traces.setBurnIn(burnin);
// TODO: Filter traces to include only dNdS columns
DnDsPerSiteAnalysis analysis = new DnDsPerSiteAnalysis(traces);
analysis.setSignificanceTest(
SignificanceTest.parseFromString(
xo.getAttribute(SIGNIFICANCE_TEST, SignificanceTest.NOT_EQUAL.getText())
)
);
analysis.setCutoff(xo.getAttribute(CUTOFF, 1.0));
analysis.setSeparator(xo.getAttribute(SEPARATOR_STRING, "\t"));
analysis.setIncludeSignificanceLevel(xo.getAttribute(INCLUDE_SIGNIFICANCE_LEVEL, false));
analysis.setIncludeSignificantSymbol(xo.getAttribute(INCLUDE_SIGNIFICANT_SYMBOL, true));
analysis.setIncludeSiteClassification(xo.getAttribute(INCLUDE_SITE_CLASSIFICATION, true));
return analysis;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
} |
package org.ow2.proactive.utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* Formatter is a class grouping tools for formatting
*
* @author The ProActive Team
* @since ProActive Scheduling 2.2
*/
public final class Formatter {
/**
* Return the stack trace of the given exception in a string.
*
* @param e
* an exception or throwable
* @return the stack trace of the given exception in a string.
*/
public static String stackTraceToString(Throwable aThrowable) {
Writer result = null;
PrintWriter printWriter = null;
try {
result = new StringWriter();
printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
} finally {
if (printWriter != null)
printWriter.close();
if (result != null)
try {
result.close();
} catch (Exception e) {
//was not able to produce the String representing the exception
System.out.println("Could not get the stacktrace for the following ex: ");
aThrowable.printStackTrace();
System.out.println("An exception occured while constructing the String representation of the exception above: ");
e.printStackTrace();
}
}
return result.toString();
}
} |
package com.coltsoftware.liquidsledgehammer.collections;
import java.util.HashMap;
public final class AliasPathResolver {
private final HashMap<String, String> mapping = new HashMap<String, String>();
public String resolve(String alias) {
String sanatizedAlias = sanitiseAlias(alias);
String path = mapping.get(sanatizedAlias);
return path == null ? pathToMissingAlias(sanatizedAlias) : path;
}
public void put(String alias, String path) {
String sanatizedAlias = sanitiseAlias(alias);
mapping.put(sanatizedAlias, path);
}
private static String pathToMissingAlias(String sanatizedAlias) {
if (sanatizedAlias.equals(""))
return "Error.Uncategorised";
return "Error.UnknownAlias." + sanatizedAlias;
}
private static String sanitiseAlias(String alias) {
return alias == null ? "" : alias;
}
} |
package droplauncher.mvc.controller;
import adakite.debugging.Debugging;
import adakite.exception.InvalidArgumentException;
import adakite.exception.InvalidStateException;
import adakite.ini.IniParseException;
import adakite.md5sum.MD5Checksum;
import adakite.util.AdakiteUtils;
import droplauncher.bwapi.BWAPI;
import droplauncher.mvc.model.Model;
import droplauncher.mvc.view.MessagePrefix;
import droplauncher.mvc.view.SettingsWindow;
import droplauncher.mvc.view.SimpleAlert;
import droplauncher.mvc.view.View;
import droplauncher.util.DropLauncher;
import adakite.util.DirectoryMonitor;
import droplauncher.exception.InvalidBotTypeException;
import droplauncher.starcraft.Starcraft;
import droplauncher.starcraft.Starcraft.Race;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import net.lingala.zip4j.core.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
public class Controller {
private static final Logger LOGGER = Logger.getLogger(Controller.class.getName());
private Model model;
private View view;
private State state;
private final Object stateLock;
private DirectoryMonitor directoryMonitor;
public Controller() {
this.model = null;
this.state = State.IDLE;
this.stateLock = new Object();
this.directoryMonitor = null;
}
public void setModel(Model model) {
this.model = model;
}
public void setView(View view) {
this.view = view;
}
/**
* Manually sets the program state indicator after acquiring
* access to an intrinsic lock object.
*
* @param state specified state
*/
private void setState(State state) {
synchronized(this.stateLock) {
this.state = state;
}
}
private void startBWHeadless() throws IOException,
InvalidBotTypeException,
IniParseException,
InvalidStateException {
setState(State.RUNNING);
this.view.getConsoleOutput().println(MessagePrefix.DROPLAUNCHER.toString() + ": connecting bot to StarCraft");
/* Init DirectoryMonitor if required. */
Path starcraftDirectory = this.model.getBWHeadless().getStarcraftDirectory();
if (this.directoryMonitor == null) {
this.directoryMonitor = new DirectoryMonitor(starcraftDirectory);
this.directoryMonitor.getIgnoreList().add("maps"); /* ignore any "*maps*" file/directory */
this.directoryMonitor.getIgnoreList().add("bwta"); /* ignore any "*bwta*" file/directory */
this.directoryMonitor.getIgnoreList().add("bwta2"); /* ignore any "*bwta2*" file/directory */
this.directoryMonitor.getIgnoreList().add("bwapi-data"); /* ignore any "*bwapi-data*" file/directory */
this.directoryMonitor.reset();
}
this.model.getBWHeadless().start(this.view.getConsoleOutput());
}
private void stopBWHeadless() throws IOException,
InvalidStateException {
setState(State.IDLE);
this.model.getBWHeadless().stop();
if (Model.isPrefEnabled(BWAPI.Property.COPY_WRITE_READ.toString())) {
/* Copy contents of "bwapi-data/write/" to "bwapi-data/read/". */
Path starcraftDirectory = this.model.getBWHeadless().getStarcraftDirectory();
Path bwapiWritePath = starcraftDirectory.resolve(BWAPI.DATA_WRITE_PATH);
Path bwapiReadPath = starcraftDirectory.resolve(BWAPI.DATA_READ_PATH);
String copyMessage = MessagePrefix.COPY.get() + bwapiWritePath.toString() + " -> " + bwapiReadPath.toString();
this.view.getConsoleOutput().println(MessagePrefix.DROPLAUNCHER.get() + copyMessage);
FileUtils.copyDirectory(bwapiWritePath.toFile(), bwapiReadPath.toFile());
}
this.view.getConsoleOutput().println(MessagePrefix.DROPLAUNCHER.get() + "ejected bot");
}
/**
* Attempts to close the specified stage. May fail if conditions are not met.
*
* @param stage specified stage to close
*/
public void closeProgramRequest(Stage stage) {
/* Check the program's current state. */
switch (this.state) {
case IDLE:
/* Do nothing. */
break;
case RUNNING:
/* Fall through. */
case LOCKED:
/* Fall through. */
default:
LOGGER.log(Debugging.getLogLevel(), "state should be " + State.IDLE.toString() + ", but state is " + this.state.toString());
new SimpleAlert().showAndWait(AlertType.ERROR, "Program state error: " + this.state.toString(), "The program's state is: " + this.state.toString() + AdakiteUtils.newline(2) + "Try ejecting the bot first or wait for the current operation to finish.");
return;
}
if (Model.isPrefEnabled(Starcraft.Property.CLEAN_SC_DIR.toString())) {
/* Clean up StarCraft directory. */
try {
if (this.directoryMonitor != null) {
Path starcraftDirectory = this.model.getBWHeadless().getStarcraftDirectory();
Path bwapiWritePath = starcraftDirectory.resolve(BWAPI.DATA_WRITE_PATH);
Path bwapiReadPath = starcraftDirectory.resolve(BWAPI.DATA_READ_PATH);
this.directoryMonitor.update();
for (Path path : this.directoryMonitor.getNewFiles()) {
if (!path.toAbsolutePath().startsWith(bwapiWritePath)
&& !path.toAbsolutePath().startsWith(bwapiReadPath)) {
/* Delete file/directory if not in the read/write directory. */
if (AdakiteUtils.fileExists(path)) {
AdakiteUtils.deleteFile(path);
} else if (AdakiteUtils.directoryExists(path)) {
FileUtils.deleteDirectory(path.toFile());
}
}
}
}
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), "clean up StarCraft directory", ex);
}
}
stage.close();
}
/**
* Reads a dropped or selected file which is meant for bwheadless and
* sets the appropiate settings.
*
* @param path specified file to process
*/
private void processFile(Path path) throws InvalidArgumentException {
if (this.state != State.IDLE) {
return;
}
String ext = AdakiteUtils.getFileExtension(path).toLowerCase(Locale.US);
if (AdakiteUtils.isNullOrEmpty(ext)) {
return;
}
switch (ext) {
case "zip":
processZipFile(path);
break;
case "dll":
/* Fall through. */
case "exe":
/* Fall through. */
case "jar":
if (path.getFileName().toString().equalsIgnoreCase("BWAPI.dll")) {
/* BWAPI.dll */
this.model.getBot().setBwapiDll(path.toAbsolutePath().toString());
} else {
/* Bot file */
this.model.getBot().setPath(path.toAbsolutePath().toString());
this.model.getBot().setName(FilenameUtils.getBaseName(path.toString()));
this.model.getBot().setRace(Race.RANDOM.toString());
}
break;
default:
/* Treat as a config file. */
this.model.getBot().addExtraFile(path.toAbsolutePath().toString());
break;
}
}
private void processZipFile(Path path) {
if (!AdakiteUtils.fileExists(path)
|| !AdakiteUtils.getFileExtension(path).equalsIgnoreCase("zip")) {
throw new IllegalArgumentException("path does not appear to be a ZIP file");
}
try {
ZipFile zipFile = new ZipFile(path.toAbsolutePath().toString());
if (zipFile.isEncrypted()) {
LOGGER.log(Debugging.getLogLevel(), "unsupported encrypted archive: " + zipFile.getFile().getAbsolutePath());
return;
}
/* Create temporary directory. */
Path tmpDir = Paths.get(DropLauncher.TEMP_DIRECTORY).toAbsolutePath();
FileUtils.deleteDirectory(tmpDir.toFile());
AdakiteUtils.createDirectory(tmpDir);
/* Extract files to temporary directory. */
zipFile.extractAll(tmpDir.toString());
/* Process contents of temporary directory. */
Path[] tmpList = AdakiteUtils.getDirectoryContents(tmpDir);
for (Path tmpPath : tmpList) {
if (!AdakiteUtils.directoryExists(tmpPath)) {
processFile(tmpPath);
}
}
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), "unable to process ZIP file: " + path.toAbsolutePath().toString(), ex);
}
}
public void filesDropped(List<File> files) {
/* Parse all objects dropped into a complete list of files dropped since
dropping a directory does NOT include all subdirectories and
files by default. */
ArrayList<Path> fileList = new ArrayList<>();
for (File file : files) {
if (file.isDirectory()) {
try {
Path[] tmpList = AdakiteUtils.getDirectoryContents(file.toPath(), true);
fileList.addAll(Arrays.asList(tmpList));
} catch (IOException ex) {
LOGGER.log(Debugging.getLogLevel(), "unable to get directory contents for: " + file.getAbsolutePath(), ex);
}
} else if (file.isFile()) {
fileList.add(file.toPath());
} else {
LOGGER.log(Debugging.getLogLevel(), "unknown file dropped: " + file.getAbsolutePath());
}
}
/* Process all files. */
for (Path path : fileList) {
try {
processFile(path);
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), null, ex);
}
}
this.view.update();
}
/* Accessible data */
/**
* Gets the manually set state indicator of the program.
*/
public State getState() {
return this.state;
}
public String getBotFilename() {
try {
String name = FilenameUtils.getName(this.model.getBot().getPath());
return name;
} catch (Exception ex) {
return null;
}
}
public String getBwapiDllVersion() {
try {
String dll = this.model.getBot().getBwapiDll();
String md5sum = MD5Checksum.get(Paths.get(dll));
String version = BWAPI.getBwapiVersion(md5sum);
return version;
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), null, ex);
return "";
}
}
public String getBotName() {
try {
String name = this.model.getBot().getName();
return name;
} catch (Exception ex) {
return null;
}
}
public Race getBotRace() {
try {
Race race = Race.get(this.model.getBot().getRace());
return race;
} catch (Exception ex) {
return null;
}
}
/* Events called by a view */
public void mnuFileSelectBotFilesClicked(Stage stage) {
FileChooser fc = new FileChooser();
fc.setTitle("Select bot files ...");
Path userDirectory = AdakiteUtils.getUserHomeDirectory();
if (userDirectory != null) {
fc.setInitialDirectory(userDirectory.toFile());
}
List<File> files = fc.showOpenMultipleDialog(stage);
if (files != null && files.size() > 0) {
try {
filesDropped(files);
} catch (Exception ex) {
/* Do nothing. */
}
}
this.view.update();
}
public void mnuFileExitClicked(Stage stage) {
closeProgramRequest(stage);
}
public void mnuEditSettingsClicked() {
new SettingsWindow().showAndWait();
}
public void mnuHelpAboutClicked() {
new SimpleAlert().showAndWait(AlertType.INFORMATION, DropLauncher.PROGRAM_TITLE, DropLauncher.PROGRAM_ABOUT);
}
public void btnStartClicked() {
/* Check if BWAPI.dll is known. */
String bwapiDllVersion = getBwapiDllVersion();
if (this.state == State.IDLE
&& Model.isPrefEnabled(BWAPI.Property.WARN_UNKNOWN_BWAPI_DLL.toString())
&& !AdakiteUtils.isNullOrEmpty(bwapiDllVersion)
&& bwapiDllVersion.equalsIgnoreCase(BWAPI.DLL_UNKNOWN)) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Warning");
alert.setContentText("The BWAPI.dll you provided does not match the list of known official BWAPI versions.\n\nDo you want to continue anyway?");
alert.setHeaderText(null);
alert.getDialogPane().getStylesheets().add(View.DEFAULT_CSS);
ButtonType btnNo = new ButtonType("No");
ButtonType btnYes = new ButtonType("Yes");
alert.getButtonTypes().setAll(btnYes, btnNo);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() != btnYes) {
new SimpleAlert().showAndWait(
AlertType.WARNING,
"Warning",
"Launch aborted!"
);
return;
}
}
State prevState = this.state;
if (prevState == State.LOCKED) {
return;
}
// boolean isReady = false;
// try {
// isReady = this.model.getBWHeadless().isReady();
// } catch (Exception ex) {
// /* Do nothing. */
// if (!isReady) {
// try {
// /* Display error message. */
// new SimpleAlert().showAndWait(
// AlertType.ERROR,
// "Not Ready",
// "The program is not ready due to the following error: " + AdakiteUtils.newline(2) +
// this.model.getBWHeadless().checkReady().toString()
// setState(State.IDLE);
// } catch (Exception ex) {
// LOGGER.log(Debugging.getLogLevel(), null, ex);
setState(State.LOCKED);
switch (prevState) {
case IDLE:
/* Start bwheadless. */
this.view.btnStartEnabled(false);
new Thread(() -> {
try {
startBWHeadless();
} catch (Exception ex) {
this.view.getConsoleOutput().println(
MessagePrefix.DROPLAUNCHER.get()
+ "unable to connect bot due to the following error:" + AdakiteUtils.newline(2)
+ ex.toString() + AdakiteUtils.newline()
);
LOGGER.log(Debugging.getLogLevel(), null, ex);
}
Platform.runLater(() -> {
this.view.btnStartSetText(View.StartButtonText.STOP.toString());
this.view.btnStartEnabled(true);
});
}).start();
return;
case RUNNING:
/* Stop bwheadless. */
this.view.btnStartEnabled(false);
new Thread(() -> {
try {
stopBWHeadless();
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), null, ex);
}
Platform.runLater(() -> {
this.view.btnStartSetText(View.StartButtonText.START.toString());
this.view.btnStartEnabled(true);
});
}).start();
return;
default:
break;
}
if (this.state == State.LOCKED) {
LOGGER.log(Debugging.getLogLevel(), "still locked");
}
}
public void botRaceChanged(String str) {
try {
this.model.getBot().setRace(str);
this.view.updateRaceChoiceBox(); //TODO: Why do we have to do this? Remove?
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), null, ex);
}
}
public void botNameChanged(String str) {
try {
this.model.getBot().setName(str);
this.view.update();
} catch (Exception ex) {
LOGGER.log(Debugging.getLogLevel(), null, ex);
}
}
} |
package net.nunnerycode.bukkit.mythicdrops.repair;
import com.comphenix.xp.rewards.xp.ExperienceManager;
import com.conventnunnery.libraries.config.CommentedConventYamlConfiguration;
import com.conventnunnery.libraries.config.ConventYamlConfiguration;
import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops;
import net.nunnerycode.java.libraries.cannonball.DebugPrinter;
import org.apache.commons.lang3.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class MythicDropsRepair extends JavaPlugin {
private DebugPrinter debugPrinter;
private Map<String, RepairItem> repairItemMap;
private Map<String, String> language;
private MythicDrops mythicDrops;
private ConventYamlConfiguration configYAML;
private boolean playSounds;
@Override
public void onDisable() {
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " disabled");
}
@Override
public void onEnable() {
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
mythicDrops = (MythicDrops) Bukkit.getPluginManager().getPlugin("MythicDrops");
repairItemMap = new HashMap<>();
language = new HashMap<>();
unpackConfigurationFiles(new String[]{"config.yml"}, false);
configYAML = new ConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().updateOnLoad(true);
configYAML.options().backupOnUpdate(true);
configYAML.load();
ConfigurationSection messages = configYAML.getConfigurationSection("messages");
if (messages != null) {
for (String key : messages.getKeys(true)) {
if (messages.isConfigurationSection(key)) {
continue;
}
language.put("messages." + key, messages.getString(key, key));
}
}
playSounds = configYAML.getBoolean("play-sounds", true);
if (!configYAML.isConfigurationSection("repair-costs")) {
defaultRepairCosts();
}
ConfigurationSection costs = configYAML.getConfigurationSection("repair-costs");
for (String key : costs.getKeys(false)) {
if (!costs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = costs.getConfigurationSection(key);
MaterialData matData = parseMaterialData(cs);
String itemName = cs.getString("item-name");
List<String> itemLore = cs.getStringList("item-lore");
List<RepairCost> costList = new ArrayList<>();
ConfigurationSection costsSection = cs.getConfigurationSection("costs");
for (String costKey : costsSection.getKeys(false)) {
if (!costsSection.isConfigurationSection(costKey)) {
continue;
}
ConfigurationSection costSection = costsSection.getConfigurationSection(costKey);
MaterialData itemCost = parseMaterialData(costSection);
int experienceCost = costSection.getInt("experience-cost", 0);
int priority = costSection.getInt("priority", 0);
int amount = costSection.getInt("amount", 1);
double repairPerCost = costSection.getDouble("repair-per-cost", 0.1);
String costName = costSection.getString("item-name");
List<String> costLore = costSection.getStringList("item-lore");
RepairCost rc = new RepairCost(costKey, priority, experienceCost, repairPerCost, amount, itemCost,
costName, costLore);
costList.add(rc);
}
RepairItem ri = new RepairItem(key, matData, itemName, itemLore);
ri.addRepairCosts(costList.toArray(new RepairCost[costList.size()]));
repairItemMap.put(ri.getName(), ri);
}
debugPrinter.debug(Level.INFO, "Loaded repair items: " + repairItemMap.keySet().size());
Bukkit.getPluginManager().registerEvents(new RepairListener(this), this);
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
private void unpackConfigurationFiles(String[] configurationFiles, boolean overwrite) {
for (String s : configurationFiles) {
YamlConfiguration yc = CommentedConventYamlConfiguration.loadConfiguration(getResource(s));
try {
File f = new File(getDataFolder(), s);
if (!f.exists()) {
yc.save(f);
continue;
}
if (overwrite) {
yc.save(f);
}
} catch (IOException e) {
getLogger().warning("Could not unpack " + s);
}
}
}
private MaterialData parseMaterialData(ConfigurationSection cs) {
String materialDat = cs.getString("material-data", "");
String materialName = cs.getString("material-name", "");
if (materialDat.isEmpty()) {
return new MaterialData(Material.getMaterial(materialName));
}
int id = 0;
byte data = 0;
String[] split = materialDat.split(";");
switch (split.length) {
case 0:
break;
case 1:
id = NumberUtils.toInt(split[0], 0);
break;
default:
id = NumberUtils.toInt(split[0], 0);
data = NumberUtils.toByte(split[1], (byte) 0);
break;
}
return new MaterialData(id, data);
}
private void defaultRepairCosts() {
Material[] wood = {Material.WOOD_AXE, Material.WOOD_HOE, Material.WOOD_PICKAXE, Material.WOOD_SPADE,
Material.WOOD_SWORD, Material.BOW, Material.FISHING_ROD};
Material[] stone = {Material.STONE_AXE, Material.STONE_PICKAXE, Material.STONE_HOE, Material.STONE_SWORD,
Material.STONE_SPADE};
Material[] leather = {Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET,
Material.LEATHER_LEGGINGS};
Material[] chain = {Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_LEGGINGS};
Material[] iron = {Material.IRON_AXE, Material.IRON_BOOTS, Material.IRON_CHESTPLATE, Material.IRON_HELMET,
Material.IRON_LEGGINGS, Material.IRON_PICKAXE, Material.IRON_HOE, Material.IRON_SPADE,
Material.IRON_SWORD};
Material[] diamond = {Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_HELMET, Material.DIAMOND_HOE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_PICKAXE,
Material.DIAMOND_SPADE, Material.DIAMOND_SWORD};
Material[] gold = {Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
Material.GOLD_LEGGINGS, Material.GOLD_PICKAXE, Material.GOLD_HOE, Material.GOLD_SPADE,
Material.GOLD_SWORD};
for (Material m : wood) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.WOOD.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : stone) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.STONE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : gold) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.GOLD_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : iron) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : diamond) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.DIAMOND.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : leather) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.LEATHER.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : chain) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_FENCE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
configYAML.save();
}
public String getLanguageString(String key, String[][] args) {
String s = getLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getLanguageString(String key) {
return language.containsKey(key) ? language.get(key) : key;
}
public String getFormattedLanguageString(String key, String[][] args) {
String s = getFormattedLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getFormattedLanguageString(String key) {
return getLanguageString(key).replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
}
public RepairItem getRepairItem(ItemStack itemStack) {
String displayName = null;
List<String> lore = new ArrayList<>();
MaterialData materialData = itemStack.getData();
MaterialData baseData = new MaterialData(itemStack.getType().getId(), (byte) 0);
if (itemStack.hasItemMeta()) {
if (itemStack.getItemMeta().hasDisplayName()) {
displayName = itemStack.getItemMeta().getDisplayName();
}
if (itemStack.getItemMeta().hasLore()) {
lore = itemStack.getItemMeta().getLore();
}
}
for (RepairItem repItem : repairItemMap.values()) {
if (!repItem.getMaterialData().equals(materialData) && !repItem.getMaterialData().equals(baseData)) {
continue;
}
if (repItem.getItemName() != null && (displayName == null || !ChatColor.translateAlternateColorCodes('&',
repItem.getName()).equals(displayName))) {
continue;
}
if (repItem.getItemLore() != null && !repItem.getItemLore().isEmpty()) {
if (lore == null) {
continue;
}
List<String> coloredLore = new ArrayList<>();
for (String s : repItem.getItemLore()) {
coloredLore.add(ChatColor.translateAlternateColorCodes('&', s));
}
if (!coloredLore.equals(lore)) {
continue;
}
}
return repItem;
}
return null;
}
private RepairCost getRepairCost(RepairItem repairItem, List<RepairCost> repairCostsList, Inventory inventory) {
RepairCost repCost = null;
for (RepairCost repairCost : repairCostsList) {
ItemStack itemStack = repairCost.toItemStack(1);
if (inventory.containsAtLeast(itemStack, repairCost.getAmount())) {
if (repCost == null) {
repCost = repairCost;
continue;
}
if (repCost.getPriority() > repairCost.getPriority()) {
repCost = repairCost;
}
}
}
return repCost;
}
protected ItemStack repairItemStack(ItemStack itemStack, Inventory inventory) {
if (itemStack == null) {
return null;
}
ItemStack repaired = itemStack.clone();
RepairItem repairItem = getRepairItem(itemStack);
if (repairItem == null) {
return repaired;
}
List<RepairCost> repairCostList = repairItem.getRepairCosts();
if (repairCostList == null) {
return repaired;
}
RepairCost repairCost = getRepairCost(repairItem, repairCostList, inventory);
if (repairCost == null) {
return repaired;
}
if (!inventory.containsAtLeast(repairCost.toItemStack(1), repairCost.getAmount())) {
return repaired;
}
int amt = repairCost.getAmount();
while (amt > 0) {
int slot = inventory.first(repairCost.toItemStack(1));
ItemStack atSlot = inventory.getItem(slot);
int atSlotAmount = atSlot.getAmount();
if (atSlotAmount < amt) {
inventory.clear(slot);
amt -= atSlotAmount;
} else {
atSlot.setAmount(atSlotAmount - amt);
amt = 0;
}
}
short currentDurability = repaired.getDurability();
short newDurability = (short) (currentDurability - repaired.getType().getMaxDurability()
* repairCost.getRepairPercentagePerCost());
repaired.setDurability((short) Math.max(newDurability, 0));
for (HumanEntity humanEntity : inventory.getViewers()) {
if (humanEntity instanceof Player) {
((Player) humanEntity).updateInventory();
}
}
return repaired;
}
public static class RepairListener implements Listener {
private MythicDropsRepair repair;
private Map<String, ItemStack> repairing;
public RepairListener(MythicDropsRepair repair) {
this.repair = repair;
repairing = new HashMap<>();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockDamageEvent(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getPlayer() == null) {
return;
}
if (event.getBlock().getType() != Material.ANVIL) {
return;
}
Player player = event.getPlayer();
if (repairing.containsKey(player.getName())) {
ItemStack oldInHand = repairing.get(player.getName());
ItemStack currentInHand = player.getItemInHand();
if (oldInHand.getType() != currentInHand.getType()) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
if (oldInHand.getDurability() == 0 || currentInHand.getDurability() == 0) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
RepairItem repairItem = repair.getRepairItem(currentInHand);
if (repairItem == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
List<RepairCost> repairCostList = repairItem.getRepairCosts();
if (repairCostList == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
RepairCost repairCost = repair.getRepairCost(repairItem, repairCostList, player.getInventory());
if (repairCost == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
if (!player.getInventory().containsAtLeast(repairItem.toItemStack(1),
repairCost.getAmount())) {
player.sendMessage(repair.getFormattedLanguageString("messages.do-not-have", new String[][]{{"%material%",
repairItem.toItemStack(1).getType().name()}}));
repairing.remove(player.getName());
return;
}
ExperienceManager experienceManager = new ExperienceManager(player);
if (!experienceManager.hasExp(repairCost.getExperienceCost())) {
player.sendMessage(repair.getFormattedLanguageString("messages.do-not-have", new String[][]{{"%material%",
repairItem.toItemStack(1).getType().name()}}));
repairing.remove(player.getName());
return;
}
experienceManager.changeExp(-repairCost.getExperienceCost());
player.setItemInHand(repair.repairItemStack(oldInHand, player.getInventory()));
player.sendMessage(repair.getFormattedLanguageString("messages.success"));
repairing.remove(player.getName());
player.updateInventory();
if (repair.playSounds) {
player.playSound(event.getBlock().getLocation(), Sound.ANVIL_USE, 1.0F, 1.0F);
}
} else {
if (player.getItemInHand().getType() == Material.AIR) {
return;
}
repairing.put(player.getName(), player.getItemInHand());
player.sendMessage(repair.getFormattedLanguageString("messages.instructions"));
}
}
}
} |
package examples.dustin.commandline.clajr;
import static java.lang.System.out;
import clajr.CLAJR;
/**
* Demonstrate use of CLAJR to process command-line arguments in Java.
*/
public class Main
{
public static void main(final String[] arguments)
{
final Options options = new Options();
try
{
CLAJR.parse(arguments, options);
out.println("File is '" + options.getFile() + "' and verbosity is set to '"
+ options.isVerbose() + "'.");
}
catch (CLAJR.EmptyArgumentListException emptyArgsEx)
{
out.println("Usage: Main -f|--file <filePathAndName> [-v|--verbose]");
}
catch (CLAJR.HelpNeededException helpNeededEx)
{
System.out.println(CLAJR.getHelp());
}
catch (CLAJR.ParseException parseEx)
{
out.println(parseEx.getMessage());
out.println(CLAJR.getHelp());
}
catch (Throwable throwable) // CLAJR.parse throws Throwable
{
out.println(throwable.getMessage());
}
}
/**
* Used reflectively by CLAJR to parse and interrogate command line
* options defined as fields in this class.
*/
public static class Options
{
private String file;
private boolean verbose;
public void _v__verbose()
{
verbose = true;
}
public String help_v__verbose()
{
return "Enables verbosity of output.";
}
public boolean isVerbose()
{
return verbose;
}
public void _f__file(String newFilePathAndName)
{
file = newFilePathAndName;
}
public String help_f__file()
{
return "Path and name of file.";
}
public String getFile()
{
return file;
}
}
} |
package owltools.ontologyverification.impl;
import static org.junit.Assert.*;
import java.util.Collection;
import org.junit.Test;
import org.semanticweb.owlapi.model.IRI;
import owltools.OWLToolsTestBasics;
import owltools.graph.OWLGraphWrapper;
import owltools.io.ParserWrapper;
import owltools.ontologyverification.CheckWarning;
import owltools.ontologyverification.OntologyCheck;
/**
* Test for {@link SelfReferenceInDefinition}.
*/
public class SelfReferenceInDefinitionTest extends OWLToolsTestBasics {
@Test
public void testSelfReferences() throws Exception {
ParserWrapper parser = new ParserWrapper();
IRI iri = IRI.create(getResource("verification/self_references.obo").getAbsoluteFile()) ;
OWLGraphWrapper graph = parser.parseToOWLGraph(iri.toString());
OntologyCheck check = new SelfReferenceInDefinition();
Collection<CheckWarning> warnings = check.check(graph, graph.getAllOWLObjects());
assertEquals(2, warnings.size());
for (CheckWarning warning : warnings) {
boolean found = false;
if (warning.getIris().contains(IRI.create("http://purl.obolibrary.org/obo/FOO_0004")) ||
warning.getIris().contains(IRI.create("http://purl.obolibrary.org/obo/FOO_0006"))) {
found = true;
}
assertTrue(found);
}
}
} |
package eu.visualize.ini.convnet;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.sun.glass.ui.CommonDialogs;
import eu.seebetter.ini.chips.ApsDvsChip;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Labels location of target using mouse GUI in recorded data for later
* supervised learning.
*
* @author tobi
*/
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
@Description("Labels location of target using mouse GUI in recorded data for later supervised learning.")
public class TargetLabeler extends EventFilter2DMouseAdaptor implements PropertyChangeListener, KeyListener {
private boolean mousePressed = false;
private boolean shiftPressed = false;
private boolean altPressed = false;
private Point mousePoint = null;
final float labelRadius = 5f;
private GLUquadric mouseQuad = null;
private TreeMap<Integer, TargetLocation> targetLocations = new TreeMap();
private TargetLocation targetLocation = null;
private ApsDvsChip apsDvsChip = null;
private int lastFrameNumber = -1;
private int lastTimestamp = Integer.MIN_VALUE;
private int currentFrameNumber = -1;
private final String LAST_FOLDER_KEY = "lastFolder";
TextRenderer textRenderer = null;
private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 10000);
private int targetRadius = getInt("targetRadius", 10);
private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 100000);
private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE;
private boolean propertyChangeListenerAdded = false;
private String DEFAULT_FILENAME = "locations.txt";
private String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
public TargetLabeler(AEChip chip) {
super(chip);
if (chip instanceof ApsDvsChip) {
apsDvsChip = ((ApsDvsChip) chip);
}
setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us");
setPropertyTooltip("targetRadius", "drawn radius of target in pixels");
setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled");
setPropertyTooltip("saveLocations", "saves target locations");
setPropertyTooltip("saveLocationsAs", "show file dialog to save target locations to a new file");
setPropertyTooltip("loadLocations", "loads locations from a file");
}
@Override
public void mouseDragged(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
public void mouseReleased(MouseEvent e) {
mousePressed = false;
}
@Override
public void mousePressed(MouseEvent e) {
mouseMoved(e);
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = (getMousePixel(e));
if (p != null) {
if (mousePoint != null) {
mousePoint.setLocation(p);
} else {
mousePoint = new Point(p);
}
} else {
mousePoint = null;
}
}
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36));
textRenderer.setColor(1, 1, 1, 1);
}
GL2 gl = drawable.getGL().getGL2();
MultilineAnnotationTextRenderer.setColor(Color.BLUE);
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .9f);
MultilineAnnotationTextRenderer.setScale(.3f);
StringBuilder sb = new StringBuilder("Shift + Alt + mouse position: specify target location\nShift: no target seen\n");
MultilineAnnotationTextRenderer.renderMultilineString(sb.toString());
MultilineAnnotationTextRenderer.renderMultilineString(String.format("%d TargetLocation samples specified\nFirst sample time: %.1fs, Last sample time: %.1fs", targetLocations.size(), minSampleTimestamp * 1e-6f, maxSampleTimestamp * 1e-6f));
if (shiftPressed && !altPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying no target");
} else if (shiftPressed && altPressed) {
MultilineAnnotationTextRenderer.renderMultilineString("Specifying target location");
} else {
MultilineAnnotationTextRenderer.renderMultilineString("Playing recorded target locations");
}
if (targetLocation != null) {
targetLocation.draw(drawable, gl);
}
}
synchronized public void doClearLocations() {
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
}
synchronized public void doSaveLocationsAs() {
JFileChooser c = new JFileChooser(lastFileName);
c.setSelectedFile(new File(lastFileName));
int ret = c.showSaveDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
if (c.getSelectedFile().exists()) {
int r = JOptionPane.showConfirmDialog(glCanvas, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?");
if (r != JOptionPane.OK_OPTION) {
return;
}
}
saveLocations(c.getSelectedFile());
}
synchronized public void doSaveLocations() {
File f = new File(lastFileName);
saveLocations(new File(lastFileName));
}
synchronized public void doLoadLocations() {
JFileChooser c = new JFileChooser(lastFileName);
c.setSelectedFile(new File(lastFileName));
int ret = c.showOpenDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
putString("lastFileName", lastFileName);
loadLocations(new File(lastFileName));
}
private TargetLocation lastNewTargetLocation = null;
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if (!propertyChangeListenerAdded) {
if (chip.getAeViewer() != null) {
chip.getAeViewer().addPropertyChangeListener(this);
propertyChangeListenerAdded = true;
}
}
for (BasicEvent e : in) {
if (e.isSpecial()) {
continue;
}
if (apsDvsChip != null) {
// update actual frame number, starting from 0 at start of recording (for playback or after rewind)
// this can be messed up by jumping in the file using slider
int newFrameNumber = apsDvsChip.getFrameCount();
if (newFrameNumber != lastFrameNumber) {
if (newFrameNumber > lastFrameNumber) {
currentFrameNumber++;
} else if (newFrameNumber < lastFrameNumber) {
currentFrameNumber
}
lastFrameNumber = newFrameNumber;
}
// show the nearest TargetLocation if at least minTargetPointIntervalUs has passed by,
// or "No target" if the location was previously
if ((long) e.timestamp - (long) lastTimestamp >= minTargetPointIntervalUs) {
lastTimestamp = e.timestamp;
// find next saved target location that is just before this time (lowerEntry)
Map.Entry<Integer, TargetLocation> mostRecentLocationBeforeThisEvent = targetLocations.lowerEntry(e.timestamp);
if (mostRecentLocationBeforeThisEvent == null || (mostRecentLocationBeforeThisEvent != null && (mostRecentLocationBeforeThisEvent.getValue() != null && (e.timestamp - mostRecentLocationBeforeThisEvent.getValue().timestamp) > maxTimeLastTargetLocationValidUs))) {
targetLocation = null;
} else {
targetLocation = mostRecentLocationBeforeThisEvent.getValue();
}
TargetLocation newTargetLocation = null;
if (shiftPressed && altPressed && mousePoint != null) {
// add a labeled location sample
maybeRemovePreviouslyRecordedSample(mostRecentLocationBeforeThisEvent, e, lastNewTargetLocation);
newTargetLocation = new TargetLocation(currentFrameNumber, e.timestamp, mousePoint);
targetLocations.put(e.timestamp, newTargetLocation);
} else if (shiftPressed && !altPressed) {
maybeRemovePreviouslyRecordedSample(mostRecentLocationBeforeThisEvent, e, lastNewTargetLocation);
newTargetLocation = new TargetLocation(currentFrameNumber, e.timestamp, null);
targetLocations.put(e.timestamp, newTargetLocation);
}
if (newTargetLocation != null) {
if (newTargetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = newTargetLocation.timestamp;
}
if (newTargetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = newTargetLocation.timestamp;
}
}
lastNewTargetLocation = newTargetLocation;
}
if (e.timestamp < lastTimestamp) {
lastTimestamp = e.timestamp;
}
}
}
return in;
}
private void maybeRemovePreviouslyRecordedSample(Map.Entry<Integer, TargetLocation> entry, BasicEvent e, TargetLocation lastSampleAdded) {
if (entry != null && entry.getValue() != lastSampleAdded && e.timestamp - entry.getKey() < minTargetPointIntervalUs) {
log.info("removing previous " + entry.getValue() + " because entry.getValue()!=lastSampleAdded=" + (entry.getValue() != lastSampleAdded) + " && timestamp difference " + (e.timestamp - entry.getKey()) + " is < " + minTargetPointIntervalUs);
targetLocations.remove(entry.getKey());
}
}
@Override
public void setSelected(boolean yes) {
super.setSelected(yes); // register/deregister mouse listeners
if (yes) {
glCanvas.addKeyListener(this);
} else {
glCanvas.removeKeyListener(this);
}
}
@Override
public void resetFilter() {
}
@Override
public void initFilter() {
}
@Override
public void propertyChange(PropertyChangeEvent evt
) {
switch (evt.getPropertyName()) {
case AEInputStream.EVENT_REWIND:
log.info("frameNumber reset to -1");
lastFrameNumber = -1;
currentFrameNumber = 0;
lastTimestamp = Integer.MIN_VALUE;
break;
case AEInputStream.EVENT_POSITION:
break;
case AEInputStream.EVENT_EOF:
}
}
/**
* @return the minTargetPointIntervalUs
*/
public int getMinTargetPointIntervalUs() {
return minTargetPointIntervalUs;
}
/**
* @param minTargetPointIntervalUs the minTargetPointIntervalUs to set
*/
public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) {
this.minTargetPointIntervalUs = minTargetPointIntervalUs;
putInt("minTargetPointIntervalUs", minTargetPointIntervalUs);
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = true;
} else if (k == KeyEvent.VK_ALT) {
altPressed = true;
}
}
@Override
public void keyReleased(KeyEvent ke) {
int k = ke.getKeyCode();
if (k == KeyEvent.VK_SHIFT) {
shiftPressed = false;
} else if (k == KeyEvent.VK_ALT) {
altPressed = false;
}
}
/**
* @return the targetRadius
*/
public int getTargetRadius() {
return targetRadius;
}
/**
* @param targetRadius the targetRadius to set
*/
public void setTargetRadius(int targetRadius) {
this.targetRadius = targetRadius;
putInt("targetRadius", targetRadius);
}
/**
* @return the maxTimeLastTargetLocationValidUs
*/
public int getMaxTimeLastTargetLocationValidUs() {
return maxTimeLastTargetLocationValidUs;
}
/**
* @param maxTimeLastTargetLocationValidUs the
* maxTimeLastTargetLocationValidUs to set
*/
public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) {
if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) {
maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs;
}
this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs;
putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs);
}
private class TargetLocationComparator implements Comparator<TargetLocation> {
@Override
public int compare(TargetLocation o1, TargetLocation o2) {
return Integer.valueOf(o1.frameNumber).compareTo(Integer.valueOf(o2.frameNumber));
}
}
private class TargetLocation {
int timestamp;
int frameNumber;
Point location;
public TargetLocation(int frameNumber, int timestamp, Point location) {
this.frameNumber = frameNumber;
this.timestamp = timestamp;
this.location = location != null ? new Point(location) : null;
}
private void draw(GLAutoDrawable drawable, GL2 gl) {
if (targetLocation.location == null) {
textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
textRenderer.draw("Target not visible", chip.getSizeX() / 2, chip.getSizeY() / 2);
textRenderer.endRendering();
return;
}
gl.glPushMatrix();
gl.glTranslatef(targetLocation.location.x, targetLocation.location.y, 0f);
gl.glColor4f(0, 1, 0, .5f);
if (mouseQuad == null) {
mouseQuad = glu.gluNewQuadric();
}
glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE);
glu.gluDisk(mouseQuad, getTargetRadius(), getTargetRadius() + 1, 32, 1);
gl.glPopMatrix();
}
public String toString() {
return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ? "null" : location.toString());
}
}
private void saveLocations(File f) {
try {
FileWriter writer = new FileWriter(f);
writer.write(String.format("# target locations\n"));
writer.write(String.format("# written %s\n", new Date().toString()));
writer.write(String.format("# frameNumber timestamp x y\n"));
for (Map.Entry<Integer, TargetLocation> entry : targetLocations.entrySet()) {
TargetLocation l = entry.getValue();
if (l.location != null) {
writer.write(String.format("%d %d %d %d\n", l.frameNumber, l.timestamp, l.location.x, l.location.y));
} else {
writer.write(String.format("%d %d null\n", l.frameNumber, l.timestamp));
}
}
writer.close();
log.info("wrote locations to file " + f.getAbsolutePath());
lastFileName = f.toString();
putString("lastFileName", lastFileName);
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't save locations", JOptionPane.WARNING_MESSAGE, null);
return;
}
}
private void loadLocations(File f) {
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String s = reader.readLine();
StringBuilder sb = new StringBuilder();
while (s != null && s.startsWith("
sb.append(s + "\n");
s = reader.readLine();
}
log.info("header lines on " + f.getAbsolutePath() + " are\n" + sb.toString());
while (s != null) {
Scanner scanner = new Scanner(s);
try {
TargetLocation targetLocation = new TargetLocation(scanner.nextInt(), scanner.nextInt(), new Point(scanner.nextInt(), scanner.nextInt())); // read target location
targetLocations.put(targetLocation.timestamp, targetLocation);
if (targetLocation != null) {
if (targetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = targetLocation.timestamp;
}
if (targetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = targetLocation.timestamp;
}
}
} catch (InputMismatchException ex) {
// infer this line is null target sample
Scanner scanner2 = new Scanner(s);
try {
TargetLocation targetLocation = new TargetLocation(scanner2.nextInt(), scanner2.nextInt(), null);
targetLocations.put(targetLocation.timestamp, targetLocation);
} catch (InputMismatchException ex2) {
throw new IOException("couldn't parse file, got InputMismatchException on line: " + s);
}
}
s = reader.readLine();
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
} catch (IOException ex) {
JOptionPane.showMessageDialog(glCanvas, ex.toString(), "Couldn't load locations", JOptionPane.WARNING_MESSAGE, null);
}
}
} |
package com.gallatinsystems.survey.device.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.http.HttpException;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.IBinder;
import android.util.Log;
import com.gallatinsystems.survey.device.R;
import com.gallatinsystems.survey.device.dao.SurveyDao;
import com.gallatinsystems.survey.device.dao.SurveyDbAdapter;
import com.gallatinsystems.survey.device.domain.Question;
import com.gallatinsystems.survey.device.domain.QuestionHelp;
import com.gallatinsystems.survey.device.domain.Survey;
import com.gallatinsystems.survey.device.exception.PersistentUncaughtExceptionHandler;
import com.gallatinsystems.survey.device.exception.TransferException;
import com.gallatinsystems.survey.device.util.ConstantUtil;
import com.gallatinsystems.survey.device.util.FileUtil;
import com.gallatinsystems.survey.device.util.HttpUtil;
import com.gallatinsystems.survey.device.util.PropertyUtil;
import com.gallatinsystems.survey.device.util.StatusUtil;
import com.gallatinsystems.survey.device.util.ViewUtil;
/**
* this activity will check for new surveys on the device and install as needed
*
* @author Christopher Fagiani
*
*/
public class SurveyDownloadService extends Service {
private static final String TAG = "SURVEY_DOWNLOAD_SERVICE";
private static final String DEFAULT_TYPE = "Survey";
private static final int COMPLETE_ID = 2;
private static final int FAIL_ID = 3;
@SuppressWarnings("unused")
private static final String NO_SURVEY = "No Survey Found";
private static final String SURVEY_LIST_SERVICE_PATH = "/surveymanager?action=getAvailableSurveysDevice&devicePhoneNumber=";
private static final String SURVEY_HEADER_SERVICE_PATH = "/surveymanager?action=getSurveyHeader&surveyId=";
private static final String DEV_ID_PARAM = "&devId=";
@SuppressWarnings("unused")
private static final String SURVEY_SERVICE_SERVICE_PATH = "/surveymanager?surveyId=";
private static final String SD_LOC = "sdcard";
private SurveyDbAdapter databaseAdaptor;
private PropertyUtil props;
private Thread thread;
private ThreadPoolExecutor downloadExecutor;
private static Semaphore lock = new Semaphore(1);
public IBinder onBind(Intent intent) {
return null;
}
/**
* life cycle method for the service. This is called by the system when the
* service is started
*/
public int onStartCommand(final Intent intent, int flags, int startid) {
thread = new Thread(new Runnable() {
public void run() {
if (intent != null) {
String surveyId = null;
if (intent.getExtras() != null) {
surveyId = intent.getExtras().getString(
ConstantUtil.SURVEY_ID_KEY);
}
checkAndDownload(surveyId);
}
}
});
thread.start();
return Service.START_REDELIVER_INTENT;
}
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(PersistentUncaughtExceptionHandler
.getInstance());
props = new PropertyUtil(getResources());
downloadExecutor = new ThreadPoolExecutor(1, 3, 5000,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* if no surveyId is passed in, this will check for new surveys and, if
* there are some new ones, downloads them to the DATA_DIR. If a surveyId is
* passed in, then that specific survey will be downloaded. If it's already
* on the device, the survey will be replaced with the new one.
*/
private void checkAndDownload(String surveyId) {
if (isAbleToRun()) {
try {
lock.acquire();
databaseAdaptor = new SurveyDbAdapter(this);
databaseAdaptor.open();
int precacheOption = Integer.parseInt(databaseAdaptor
.findPreference(ConstantUtil.PRECACHE_SETTING_KEY));
String serverBase = databaseAdaptor
.findPreference(ConstantUtil.SERVER_SETTING_KEY);
if (serverBase != null && serverBase.trim().length() > 0) {
serverBase = getResources().getStringArray(R.array.servers)[Integer
.parseInt(serverBase)];
} else {
serverBase = props.getProperty(ConstantUtil.SERVER_BASE);
}
int surveyCheckOption = Integer.parseInt(databaseAdaptor
.findPreference(ConstantUtil.CHECK_FOR_SURVEYS));
String deviceId = databaseAdaptor
.findPreference(ConstantUtil.DEVICE_IDENT_KEY);
ArrayList<Survey> surveys = null;
if (surveyId != null && surveyId.trim().length() > 0) {
surveys = getSurveyHeader(serverBase, surveyId, deviceId);
if (surveys != null && surveys.size() > 0) {
// if we already have the survey, delete it first
databaseAdaptor.deleteSurvey(surveyId.trim(), true);
}
} else {
if (canDownload(surveyCheckOption)) {
surveys = checkForSurveys(serverBase, deviceId);
}
}
if (surveys != null && surveys.size() > 0) {
// if there are surveys for this device, see if we need
// them
surveys = databaseAdaptor.checkSurveyVersions(surveys);
int updateCount = 0;
if (surveys != null && surveys.size() > 0) {
for (int i = 0; i < surveys.size(); i++) {
Survey survey = surveys.get(i);
try {
if (downloadSurvey(serverBase, survey)) {
databaseAdaptor.saveSurvey(survey);
downloadHelp(survey, precacheOption);
updateCount++;
}
} catch (Exception e) {
Log.e(TAG, "Could not download survey", e);
PersistentUncaughtExceptionHandler
.recordException(e);
}
}
if (updateCount > 0) {
fireNotification(updateCount);
}
}
}
// now check if any previously downloaded surveys still need
// don't have their help media pre-cached
if (canDownload(precacheOption)) {
surveys = databaseAdaptor.listSurveys(null);
if (surveys != null) {
for (int i = 0; i < surveys.size(); i++) {
if (!surveys.get(i).isHelpDownloaded()) {
downloadHelp(surveys.get(i), precacheOption);
}
}
}
}
databaseAdaptor.close();
} catch (Exception e) {
Log.e(TAG, "Could not update surveys", e);
PersistentUncaughtExceptionHandler.recordException(e);
} finally {
lock.release();
}
}
try {
downloadExecutor.shutdown();
// wait up to 30 minutes to download the media
downloadExecutor.awaitTermination(1800, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e(TAG,
"Error while waiting for download executor to terminate", e);
}
stopSelf();
}
/**
* Downloads the survey based on the ID and then updates the survey object
* with the filename and location
*/
private boolean downloadSurvey(String serverBase, Survey survey) {
boolean success = false;
try {
HttpUtil.httpDownload(
props.getProperty(ConstantUtil.SURVEY_S3_URL)
+ survey.getId() + ConstantUtil.ARCHIVE_SUFFIX,
FileUtil.getFileOutputStream(
survey.getId() + ConstantUtil.ARCHIVE_SUFFIX,
ConstantUtil.DATA_DIR,
props.getProperty(ConstantUtil.USE_INTERNAL_STORAGE),
this));
extractAndSave(FileUtil.getFileInputStream(survey.getId()
+ ConstantUtil.ARCHIVE_SUFFIX, ConstantUtil.DATA_DIR,
props.getProperty(ConstantUtil.USE_INTERNAL_STORAGE), this));
survey.setFileName(survey.getId() + ConstantUtil.XML_SUFFIX);
survey.setType(DEFAULT_TYPE);
survey.setLocation(SD_LOC);
success = true;
} catch (IOException e) {
Log.e(TAG, "Could write survey file " + survey.getFileName(), e);
String text = getResources().getString(R.string.cannotupdate);
ViewUtil.fireNotification(text, text, this, FAIL_ID, null);
PersistentUncaughtExceptionHandler
.recordException(new TransferException(survey.getId(),
null, e));
} catch (Exception e) {
Log.e(TAG, "Could not download survey " + survey.getId(), e);
String text = getResources().getString(R.string.cannotupdate);
ViewUtil.fireNotification(text, text, this, FAIL_ID, null);
PersistentUncaughtExceptionHandler
.recordException(new TransferException(survey.getId(),
null, e));
}
return success;
}
/**
* reads the byte array passed in using a zip input stream and extracts the
* entry to the file specified. This assumes ONE entry per zip
*
* @param bytes
* @param f
* @throws IOException
*/
private void extractAndSave(FileInputStream zipFile) throws IOException {
ZipInputStream zis = new ZipInputStream(zipFile);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
FileOutputStream fout = FileUtil.getFileOutputStream(
entry.getName(), ConstantUtil.DATA_DIR,
props.getProperty(ConstantUtil.USE_INTERNAL_STORAGE), this);
byte[] buffer = new byte[2048];
int size;
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
fout.write(buffer, 0, size);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
/**
* checks to see if we should pre-cache help media files (based on the
* property in the settings db) and, if we should, downloads the files
*
* @param survey
*/
private void downloadHelp(Survey survey, int precacheOption) {
// first, see if we should even bother trying to download
if (canDownload(precacheOption)) {
try {
InputStream in = null;
if (ConstantUtil.RESOURCE_LOCATION.equalsIgnoreCase(survey
.getLocation())) {
// load from resource
Resources res = getResources();
in = res.openRawResource(res.getIdentifier(
survey.getFileName(), ConstantUtil.RAW_RESOURCE,
ConstantUtil.RESOURCE_PACKAGE));
} else {
// load from file
in = FileUtil
.getFileInputStream(
survey.getFileName(),
ConstantUtil.DATA_DIR,
props.getProperty(ConstantUtil.USE_INTERNAL_STORAGE),
this);
}
Survey hydratedSurvey = SurveyDao.loadSurvey(survey, in);
if (hydratedSurvey != null) {
// collect files in a set just in case the same binary is
// used in multiple questions
// we only need to download once
HashSet<String> fileSet = new HashSet<String>();
if (hydratedSurvey.getQuestionGroups() != null) {
for (int i = 0; i < hydratedSurvey.getQuestionGroups()
.size(); i++) {
ArrayList<Question> questions = hydratedSurvey
.getQuestionGroups().get(i).getQuestions();
if (questions != null) {
for (int j = 0; j < questions.size(); j++) {
if (questions
.get(j)
.getHelpByType(
ConstantUtil.VIDEO_HELP_TYPE)
.size() > 0) {
fileSet.add(questions
.get(j)
.getHelpByType(
ConstantUtil.VIDEO_HELP_TYPE)
.get(0).getValue());
}
ArrayList<QuestionHelp> helpList = questions
.get(j)
.getHelpByType(
ConstantUtil.IMAGE_HELP_TYPE);
ArrayList<String> images = new ArrayList<String>();
for (int x = 0; x < helpList.size(); x++) {
images.add(helpList.get(x).getValue());
}
if (images != null) {
for (int k = 0; k < images.size(); k++) {
fileSet.add(images.get(k));
}
}
}
}
}
}
for (String file : fileSet) {
downloadBinary(file, survey.getId());
}
databaseAdaptor.markSurveyHelpDownloaded(survey.getId(),
true);
}
} catch (FileNotFoundException e) {
Log.e(TAG, "Could not parse survey survey file", e);
PersistentUncaughtExceptionHandler.recordException(e);
}
}
}
/**
* uses the thread pool executor to download the remote file passed in via a
* background thread
*
* @param remoteFile
* @param surveyId
*/
private void downloadBinary(final String remoteFile, final String surveyId) {
try {
final FileOutputStream out = FileUtil.getFileOutputStream(
remoteFile.substring(remoteFile.lastIndexOf("/") + 1),
ConstantUtil.DATA_DIR + surveyId + "/",
props.getProperty(ConstantUtil.USE_INTERNAL_STORAGE), this);
downloadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
HttpUtil.httpDownload(remoteFile, out);
} catch (Exception e) {
Log.e(TAG, "Could not download help media file", e);
}
}
});
} catch (FileNotFoundException e1) {
Log.e(TAG, "Could not download binary file", e1);
PersistentUncaughtExceptionHandler.recordException(e1);
}
}
/**
* invokes a service call to get the header information for a single survey
*
* @param serverBase
* @param surveyId
* @return
*/
private ArrayList<Survey> getSurveyHeader(String serverBase,
String surveyId, String deviceId) {
String response = null;
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
response = HttpUtil.httpGet(serverBase + SURVEY_HEADER_SERVICE_PATH
+ surveyId + "&devicePhoneNumber="
+ StatusUtil.getPhoneNumber(this)
+ (deviceId != null ? (DEV_ID_PARAM + deviceId) : ""));
if (response != null) {
StringTokenizer strTok = new StringTokenizer(response, "\n");
while (strTok.hasMoreTokens()) {
String currentLine = strTok.nextToken();
String[] touple = currentLine.split(",");
if (touple.length < 4) {
Log.e(TAG,
"Survey list response is in an unrecognized format");
} else {
Survey temp = new Survey();
temp.setId(touple[0]);
temp.setName(touple[1]);
temp.setLanguage(touple[2]);
temp.setVersion(Double.parseDouble(touple[3]));
temp.setType(ConstantUtil.FILE_SURVEY_LOCATION_TYPE);
surveys.add(temp);
}
}
}
} catch (HttpException e) {
Log.e(TAG, "Server returned an unexpected response", e);
PersistentUncaughtExceptionHandler.recordException(e);
} catch (Exception e) {
Log.e(TAG, "Could not get survey headers", e);
PersistentUncaughtExceptionHandler.recordException(e);
}
return surveys;
}
/**
* invokes a service call to list all surveys that have been designated for
* this device (based on phone number).
*
* @return - an arrayList of Survey objects with the id and version
* populated
*/
private ArrayList<Survey> checkForSurveys(String serverBase, String deviceId) {
String response = null;
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
response = HttpUtil.httpGet(serverBase + SURVEY_LIST_SERVICE_PATH
+ StatusUtil.getPhoneNumber(this)
+ (deviceId != null ? DEV_ID_PARAM + deviceId : ""));
if (response != null) {
StringTokenizer strTok = new StringTokenizer(response, "\n");
while (strTok.hasMoreTokens()) {
String currentLine = strTok.nextToken();
String[] touple = currentLine.split(",");
if (touple.length < 5) {
Log.e(TAG,
"Survey list response is in an unrecognized format");
} else {
Survey temp = new Survey();
temp.setId(touple[1]);
temp.setName(touple[2]);
temp.setLanguage(touple[3]);
temp.setVersion(Double.parseDouble(touple[4]));
temp.setType(ConstantUtil.FILE_SURVEY_LOCATION_TYPE);
surveys.add(temp);
}
}
}
} catch (HttpException e) {
Log.e(TAG, "Server returned an unexpected response", e);
PersistentUncaughtExceptionHandler.recordException(e);
} catch (Exception e) {
Log.e(TAG, "Could not download survey", e);
PersistentUncaughtExceptionHandler.recordException(e);
}
return surveys;
}
/**
* displays a notification in the system status bar indicating the
* completion of the download operation
*
* @param type
*/
private void fireNotification(int count) {
String text = getResources().getText(R.string.surveysupdated)
.toString();
ViewUtil.fireNotification(text, text, this, COMPLETE_ID, null);
}
/**
* this method checks if the service can perform the requested operation. If
* there is no connectivity, this will return false, otherwise it will
* return true
*
*
* @param type
* @return
*/
private boolean isAbleToRun() {
return StatusUtil.hasDataConnection(this, false);
}
/**
* this method checks if the service can precache media files based on the
* user preference and the type of network connection currently held
*
* @param type
* @return
*/
private boolean canDownload(int precacheOptionIndex) {
boolean ok = false;
if (precacheOptionIndex > -1
&& ConstantUtil.PRECACHE_WIFI_ONLY_IDX == precacheOptionIndex) {
ok = StatusUtil.hasDataConnection(this, true);
} else {
ok = StatusUtil.hasDataConnection(this, false);
}
return ok;
}
} |
package be.ecam.ecalendar;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import be.ecam.ecalendar.CalendarContract.CalendarTypeEntry;
import be.ecam.ecalendar.CalendarContract.ScheduleEntry;
public class CalendarDAO {
private static final String TAG = CalendarDAO.class.getSimpleName();
private static final String LAST_SAVED_PREF_FILE_KEY = "last_saved_query";
private static final String LAST_SAVED_TYPES_ID = "types";
private static final String LAST_SAVED_CALENDAR_ID = "calendar-";
// In milliseconds.
private static final int TIME_BEFORE_RELOAD = 1000 * 60 * 60 * 24 * 7;
private static CalendarDAO singleton;
private Context context;
private CalendarDataUpdated notifier;
private CalendarDBHelper dbHelper;
private SQLiteDatabase db;
private HashMap<String, ArrayList<Schedule>> calendars;
private HashMap<String, ArrayList<CalendarType>> types;
private long lastSavedTimeTypes;
private SharedPreferences lastTimePref;
private CalendarDAO(Context context, CalendarDataUpdated notifier) {
this.context = context;
this.notifier = notifier;
dbHelper = new CalendarDBHelper(context);
db = dbHelper.getWritableDatabase();
calendars = new HashMap<>();
types = new HashMap<>();
loadTypesFromDB();
lastTimePref = context.getSharedPreferences(LAST_SAVED_PREF_FILE_KEY,
Context.MODE_PRIVATE);
lastSavedTimeTypes = lastTimePref.getLong(LAST_SAVED_TYPES_ID, 0);
}
public static CalendarDAO createSingleton(Context context, CalendarDataUpdated notifier) {
if (singleton != null) {
return singleton;
}
singleton = new CalendarDAO(context, notifier);
return singleton;
}
public static CalendarDAO getSingleton() {
return singleton;
}
public interface CalendarDataUpdated {
void notifySchedulesChange(String name, ArrayList<Schedule> schedules);
}
public HashMap<String, ArrayList<CalendarType>> getCalendarTypes() {
long current = new Date().getTime();
if (types.isEmpty() || current - lastSavedTimeTypes > TIME_BEFORE_RELOAD) {
downloadTypesData();
} else {
loadTypesFromDB();
}
return types;
}
public ArrayList<Schedule> getCalendar(String name) {
long lastSaved = lastTimePref.getLong(LAST_SAVED_CALENDAR_ID + name, 0);
long current = new Date().getTime();
if (calendars.get(name) == null) {
calendars.put(name, new ArrayList<Schedule>());
}
if (calendars.get(name).isEmpty()) {
if (current - lastSaved > TIME_BEFORE_RELOAD) {
downloadCalendar(name);
} else {
loadCalendarFromDB(name);
}
}
return calendars.get(name);
}
private void downloadTypesData() {
Intent intent = new Intent(context, CalendarLoader.class);
intent.putExtra("action", "type");
context.startService(intent);
}
private void loadTypesFromDB() {
for (ArrayList<CalendarType> type : types.values()) {
type.clear();
}
// Get everythings from CalendarType table.
Cursor cursor = db.query(CalendarTypeEntry.TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String type = cursor.getString(cursor.getColumnIndex(CalendarTypeEntry.CALENDAR_TYPE_TYPE));
String id = cursor.getString(cursor.getColumnIndex(CalendarTypeEntry.CALENDAR_TYPE_ID));
String desc = cursor.getString(cursor.getColumnIndex(CalendarTypeEntry.CALENDAR_TYPE_DESCRIPTION));
if (types.get(type) == null) {
types.put(type, new ArrayList<CalendarType>());
}
types.get(type).add(new CalendarType(id, desc));
cursor.moveToNext();
}
}
private void downloadCalendar(String name) {
Intent intent = new Intent(context, CalendarLoader.class);
intent.putExtra("action", "schedule");
intent.putExtra("name", name);
context.startService(intent);
}
private void loadCalendarFromDB(String name) {
calendars.get(name).clear();
Cursor cursor = db.query(ScheduleEntry.TABLE_NAME, null,
ScheduleEntry.SCHEDULE_CALENDAR + "=?", new String[] {name}, null, null, null);
while (cursor.moveToNext()) {
calendars.get(name).add(new Schedule(
cursor.getString(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_CALENDAR)),
name,
new Date(cursor.getLong(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_START_TIME))),
new Date(cursor.getLong(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_END_TIME))),
cursor.getString(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_ACTIVITY_NAME)),
cursor.getString(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_GROUP)),
cursor.getString(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_TEACHER)),
cursor.getString(cursor.getColumnIndex(ScheduleEntry.SCHEDULE_CLASS_ROOM))
));
}
}
private void saveLastQueryTime(String id) {
SharedPreferences.Editor editor = lastTimePref.edit();
editor.putLong(id, new Date().getTime());
editor.commit();
}
public void updateCalendarType(HashMap<String, ArrayList<CalendarType>> types) {
// Update in-memory representation.
this.types = types;
// Delete all data associated to calendar type.
db.delete(CalendarTypeEntry.TABLE_NAME, null, null);
for (Map.Entry<String, ArrayList<CalendarType>> entry : types.entrySet()) {
String type = entry.getKey();
for (CalendarType typeData : removeDuplicate(entry.getValue())) {
ContentValues values = new ContentValues();
values.put(CalendarTypeEntry.CALENDAR_TYPE_ID, typeData.getId());
values.put(CalendarTypeEntry.CALENDAR_TYPE_DESCRIPTION, typeData.getDescription());
values.put(CalendarTypeEntry.CALENDAR_TYPE_TYPE, type);
db.insert(CalendarTypeEntry.TABLE_NAME, null, values);
}
}
saveLastQueryTime(LAST_SAVED_TYPES_ID);
lastSavedTimeTypes = new Date().getTime();
}
private ArrayList<CalendarType> removeDuplicate(ArrayList<CalendarType> types) {
ArrayList<CalendarType> newData = new ArrayList<>();
for (CalendarType type : types) {
boolean found = false;
for (CalendarType data : newData) {
if (type.getId().equals(data.getId())) {
found = true;
}
}
if (! found) {
newData.add(type);
}
}
return newData;
}
public void updateCalendar(String name, ArrayList<Schedule> schedules) {
// Update in-memory data
calendars.put(name, schedules);
// Notify that data has changed
notifier.notifySchedulesChange(name, schedules);
// Remove previously saved calendar data with the name.
db.delete(ScheduleEntry.TABLE_NAME,
ScheduleEntry.SCHEDULE_CALENDAR + "=?", new String[] { name });
for (Schedule sched : schedules) {
ContentValues values = new ContentValues();
values.put(ScheduleEntry.SCHEDULE_ACTIVITY_ID, sched.getActivityId());
values.put(ScheduleEntry.SCHEDULE_CALENDAR, name);
values.put(ScheduleEntry.SCHEDULE_ACTIVITY_NAME, sched.getActivityName());
values.put(ScheduleEntry.SCHEDULE_START_TIME, sched.getStartTime().getTime());
values.put(ScheduleEntry.SCHEDULE_END_TIME, sched.getStartTime().getTime());
values.put(ScheduleEntry.SCHEDULE_GROUP, sched.getGroup());
values.put(ScheduleEntry.SCHEDULE_CLASS_ROOM, sched.getGroup());
values.put(ScheduleEntry.SCHEDULE_TEACHER, sched.getTeacher());
db.insert(ScheduleEntry.TABLE_NAME, null, values);
}
saveLastQueryTime(LAST_SAVED_CALENDAR_ID + name);
}
} |
package com.quipmate2.features;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.quipmate2.R;
import com.quipmate2.constants.AppProperties;
import com.quipmate2.utils.CommonMethods;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SignUp extends Activity implements OnClickListener {
private EditText etemail;
private Button btsignup;
private TextView codehave;
private JSONArray result;
private JSONObject data;
private Session signup;
private String code,mobile;
private Session session;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActionBar().setTitle("Malaviyan Login");
setContentView(R.layout.signup);
getActionBar().setDisplayHomeAsUpEnabled(true);
signup = new Session(SignUp.this);
etemail = (EditText) findViewById(R.id.etemail_signup);
btsignup = (Button) findViewById(R.id.blogin_signup);
codehave = (TextView) findViewById(R.id.code_got);
btsignup.setOnClickListener(this);
codehave.setOnClickListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.blogin_signup){
mobile = etemail.getText().toString().trim();
if(mobile !=null){
new sendEmail().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
else if(v.getId() == R.id.code_got){
//show dialog here
AlertDialog.Builder codeDialog = new AlertDialog.Builder(this);
codeDialog.setTitle("VALIDATION");
codeDialog.setMessage("Enter the 4 digit code");
final EditText input = new EditText(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
codeDialog.setView(input);
codeDialog.setIcon(R.drawable.ic_status);
codeDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
code = input.getText().toString();
new verifyCode().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
codeDialog.show();
}
}
class verifyCode extends AsyncTask<Void, Void, Void>{
ProgressDialog pdialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pdialog = new ProgressDialog(SignUp.this);
pdialog.setMessage("Verifying the code");
pdialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
apiParams.add(new BasicNameValuePair(AppProperties.ACTION, "malaviyan_login"));
apiParams.add(new BasicNameValuePair("mobile", mobile));
apiParams.add(new BasicNameValuePair("code", code));
result = CommonMethods.loadJSONData(AppProperties.URL, AppProperties.METHOD_GET, apiParams);
if(result != null){
data = result.getJSONObject(0);
System.out.println(data);
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progressBar = (ProgressBar) findViewById(R.id.progressbar);
session = new Session(SignUp.this);
if(pdialog.isShowing())
pdialog.dismiss();
try {
Log.e("Code", data.toString());
if (data != null && data.has(AppProperties.ACK)) {
session.setValue(AppProperties.PARAM_EMAIL, data.getString(AppProperties.PARAM_EMAIL));
session.setValue(AppProperties.MY_PROFILE_NAME,
data.getString(AppProperties.MY_PROFILE_NAME));
session.setValue(AppProperties.MY_PROFILE_PIC,
data.getString(AppProperties.MY_PROFILE_PIC));
session.setValue(AppProperties.SESSION_ID,
data.getString(AppProperties.SESSION_ID));
session.setValue(AppProperties.PROFILE_ID,
data.getString(AppProperties.MY_PROFILE_ID));
session.setValue(AppProperties.SESSION_NAME,
data.getString(AppProperties.SESSION_NAME));
session.setValue(AppProperties.DATABASE,
data.getString(AppProperties.DATABASE));
if (session.commit()) {
startService(new Intent(SignUp.this, RealTimeService.class));
startService(new Intent(SignUp.this, ChatService.class));
Intent intent = new Intent(SignUp.this, WelcomeActivity.class);
startActivity(intent);
finish();
} else {
CommonMethods.ShowInfo(SignUp.this, "Some problem in Login. Please try again.").show();
}
} else if (data.has(getString(R.string.error))) {
JSONObject error = data
.getJSONObject(getString(R.string.error));
if (error.getString(getString(R.string.code)).equals(
AppProperties.WRONG_CREDENTIAL_CODE)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
progressBar.setVisibility(View.INVISIBLE);
CommonMethods.ShowInfo(SignUp.this,
getString(R.string.invalid_credential))
.show();
}
});
}
}
}
catch(Exception e){
System.out.println(e);
}
}
}
class sendEmail extends AsyncTask<Void, Void, Void>{
ProgressDialog pdialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pdialog = new ProgressDialog(SignUp.this);
pdialog.setMessage("Please Wait");
pdialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
apiParams.add(new BasicNameValuePair(AppProperties.ACTION, "malaviyan_litmus_test"));
apiParams.add(new BasicNameValuePair("mobile", mobile));
result = CommonMethods.loadJSONData(AppProperties.URL, AppProperties.METHOD_GET, apiParams);
if(result != null){
data=result.getJSONObject(0);
System.out.println(data);
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(pdialog.isShowing())
pdialog.dismiss();
try{
Log.e("Code", data.toString());
if(data != null && data.has(AppProperties.ACK)){
//save the code and email if user wishes to validate the code later.
signup.setValue("user_email_signup", mobile);
signup.commit();
System.out.println(code);
CommonMethods.ShowInfo(SignUp.this, "A 4 digit code has been sent to your email").show();
}
else{
CommonMethods.ShowInfo(SignUp.this, "Something went wrong. Please try again.").show();
}
}
catch(Exception e){
System.out.println(e);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.