diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/VASSAL/chat/peer2peer/DirectPeerPool.java b/src/VASSAL/chat/peer2peer/DirectPeerPool.java
index 9aecfed3..bdc78694 100644
--- a/src/VASSAL/chat/peer2peer/DirectPeerPool.java
+++ b/src/VASSAL/chat/peer2peer/DirectPeerPool.java
@@ -1,155 +1,155 @@
/*
*
* Copyright (c) 2000-2007 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.chat.peer2peer;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import org.litesoft.p2pchat.PeerInfo;
import org.litesoft.p2pchat.PendingPeerManager;
import VASSAL.build.GameModule;
import VASSAL.chat.HttpRequestWrapper;
import VASSAL.chat.ui.ChatControlsInitializer;
import VASSAL.chat.ui.ChatServerControls;
import VASSAL.i18n.Resources;
/**
* Date: Mar 12, 2003
*/
public class DirectPeerPool implements PeerPool, ChatControlsInitializer {
private AcceptPeerThread acceptThread;
private JButton inviteButton;
private JDialog frame;
private String myIp;
public DirectPeerPool() {
inviteButton = new JButton(Resources.getString("Peer2Peer.invite_players")); //$NON-NLS-1$
inviteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
inviteButton.setEnabled(false);
}
public void initialize(P2PPlayer myInfo, PendingPeerManager ppm) throws IOException {
myIp = myInfo.getInfo().getAddresses();
try {
myIp = discoverMyIpAddressFromRemote();
}
// FIXME: review error message
catch (IOException e) {
}
acceptThread = new AcceptPeerThread(myInfo.getInfo().getPort(), ppm);
myInfo.getInfo().setPort(acceptThread.getPort());
acceptThread.start();
if (frame == null) {
initComponents(myInfo, ppm);
inviteButton.setEnabled(true);
}
}
private String discoverMyIpAddressFromRemote() throws IOException {
String theIp = null;
HttpRequestWrapper r = new HttpRequestWrapper("http://www.vassalengine.org/util/getMyAddress"); //$NON-NLS-1$
List<String> l = r.doGet(null);
if (!l.isEmpty()) {
theIp = l.get(0);
}
else {
throw new IOException(Resources.getString("Server.empty_response")); //$NON-NLS-1$
}
return theIp;
}
public void disconnect() {
if (frame != null) {
frame.dispose();
frame = null;
inviteButton.setEnabled(false);
}
if (acceptThread != null) {
acceptThread.halt();
acceptThread = null;
}
}
public void connectFailed(PeerInfo peerInfo) {
JOptionPane.showMessageDialog(frame, Resources.getString("Peer2Peer.could_not_reach", peerInfo.getAddresses(), String.valueOf(peerInfo.getPort())), //$NON-NLS-1$
Resources.getString("Peer2Peer.invite_failed"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$
}
public void initComponents(final P2PPlayer me, final PendingPeerManager ppm) {
Frame owner = null;
if (GameModule.getGameModule() != null) {
owner = GameModule.getGameModule().getFrame();
}
frame = new JDialog(owner,Resources.getString("Peer2Peer.direct_connection")); //$NON-NLS-1$
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.add(createLabel(Resources.getString("Peer2Peer.your_ip_address", myIp, String.valueOf(me.getInfo().getPort())))); //$NON-NLS-1$
frame.add(createLabel(Resources.getString("Peer2Peer.other_players_address"))); //$NON-NLS-1$
Box b = Box.createHorizontalBox();
b.setAlignmentX(0.0f);
JButton invite = new JButton(Resources.getString("Peer2Peer.invite")); //$NON-NLS-1$
b.add(invite);
final JTextField tf = new JTextField(Resources.getString("Peer2Peer.address_port")); //$NON-NLS-1$
b.add(tf);
frame.add(b);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
- PeerInfo info = PeerInfo.deFormat(tf.getText());
+ PeerInfo info = PeerInfo.deFormat(tf.getText().replaceAll("\\s", "")); //$NON-NLS-1$ //$NON-NLS-2$
if (info != null) {
ppm.addNewPeer(info);
tf.setText(""); //$NON-NLS-1$
}
else {
JOptionPane.showMessageDialog(frame, Resources.getString("Peer2Peer.invalid_format")); //$NON-NLS-1$
}
}
};
invite.addActionListener(al);
tf.addActionListener(al);
frame.pack();
frame.setLocationRelativeTo(owner);
}
private JLabel createLabel(String text) {
JLabel l = new JLabel(text);
l.setAlignmentX(0.0f);
return l;
}
public void initializeControls(ChatServerControls controls) {
controls.getToolbar().add(inviteButton);
}
public void uninitializeControls(ChatServerControls controls) {
controls.getToolbar().remove(inviteButton);
}
}
| true | true | public void initComponents(final P2PPlayer me, final PendingPeerManager ppm) {
Frame owner = null;
if (GameModule.getGameModule() != null) {
owner = GameModule.getGameModule().getFrame();
}
frame = new JDialog(owner,Resources.getString("Peer2Peer.direct_connection")); //$NON-NLS-1$
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.add(createLabel(Resources.getString("Peer2Peer.your_ip_address", myIp, String.valueOf(me.getInfo().getPort())))); //$NON-NLS-1$
frame.add(createLabel(Resources.getString("Peer2Peer.other_players_address"))); //$NON-NLS-1$
Box b = Box.createHorizontalBox();
b.setAlignmentX(0.0f);
JButton invite = new JButton(Resources.getString("Peer2Peer.invite")); //$NON-NLS-1$
b.add(invite);
final JTextField tf = new JTextField(Resources.getString("Peer2Peer.address_port")); //$NON-NLS-1$
b.add(tf);
frame.add(b);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
PeerInfo info = PeerInfo.deFormat(tf.getText());
if (info != null) {
ppm.addNewPeer(info);
tf.setText(""); //$NON-NLS-1$
}
else {
JOptionPane.showMessageDialog(frame, Resources.getString("Peer2Peer.invalid_format")); //$NON-NLS-1$
}
}
};
invite.addActionListener(al);
tf.addActionListener(al);
frame.pack();
frame.setLocationRelativeTo(owner);
}
| public void initComponents(final P2PPlayer me, final PendingPeerManager ppm) {
Frame owner = null;
if (GameModule.getGameModule() != null) {
owner = GameModule.getGameModule().getFrame();
}
frame = new JDialog(owner,Resources.getString("Peer2Peer.direct_connection")); //$NON-NLS-1$
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.add(createLabel(Resources.getString("Peer2Peer.your_ip_address", myIp, String.valueOf(me.getInfo().getPort())))); //$NON-NLS-1$
frame.add(createLabel(Resources.getString("Peer2Peer.other_players_address"))); //$NON-NLS-1$
Box b = Box.createHorizontalBox();
b.setAlignmentX(0.0f);
JButton invite = new JButton(Resources.getString("Peer2Peer.invite")); //$NON-NLS-1$
b.add(invite);
final JTextField tf = new JTextField(Resources.getString("Peer2Peer.address_port")); //$NON-NLS-1$
b.add(tf);
frame.add(b);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
PeerInfo info = PeerInfo.deFormat(tf.getText().replaceAll("\\s", "")); //$NON-NLS-1$ //$NON-NLS-2$
if (info != null) {
ppm.addNewPeer(info);
tf.setText(""); //$NON-NLS-1$
}
else {
JOptionPane.showMessageDialog(frame, Resources.getString("Peer2Peer.invalid_format")); //$NON-NLS-1$
}
}
};
invite.addActionListener(al);
tf.addActionListener(al);
frame.pack();
frame.setLocationRelativeTo(owner);
}
|
diff --git a/src/main/java/ir/xweb/module/LogModule.java b/src/main/java/ir/xweb/module/LogModule.java
index ddb038e..c5fe154 100755
--- a/src/main/java/ir/xweb/module/LogModule.java
+++ b/src/main/java/ir/xweb/module/LogModule.java
@@ -1,89 +1,89 @@
/**
* XWeb project
* https://github.com/abdollahpour/xweb
* Hamed Abdollahpour - 2013
*/
package ir.xweb.module;
import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Math;
import java.util.HashMap;
import java.io.File;
public class LogModule extends Module {
private final static Logger logger = LoggerFactory.getLogger(LogModule.class);
private final static String SESSION_LAST_POSITION = "module_log_position_";
private final static int MAX_READ = 30 * 1024;
private File log;
public LogModule(
final Manager manager,
final ModuleInfo info,
final ModuleParam properties) throws ModuleException {
super(manager, info, properties);
String path = properties.getString("path", null);
log = new File(path);
}
@Override
public void process(
final ServletContext context,
final HttpServletRequest request,
final HttpServletResponse response,
final ModuleParam params,
final HashMap<String, FileItem> files) throws IOException {
/** We have different log history for different IDs, so we can have different HTMLs **/
- final int id = params.getInt("id", 0);
+ final String id = params.getString("id", "0");
if(log != null && log.exists()) {
response.setContentType("text/plain");
long last = log.lastModified();
long len = log.length();
Long position = (Long) request.getSession().getAttribute(SESSION_LAST_POSITION + id);
// init
if(position == null) {
position = Math.max(0, len - MAX_READ);
}
final PrintWriter writer = response.getWriter();
final FileReader reader = new FileReader(log);
if(position > 0) {
reader.skip(position);
}
char[] buffer = new char[1024];
int size;
while((size = reader.read(buffer)) > 0) {
writer.write(buffer, 0, size);
position += size;
}
request.getSession().setAttribute(SESSION_LAST_POSITION + id, position);
reader.close();
} else {
logger.error("Log file not found: " + log);
}
}
}
| true | true | public void process(
final ServletContext context,
final HttpServletRequest request,
final HttpServletResponse response,
final ModuleParam params,
final HashMap<String, FileItem> files) throws IOException {
/** We have different log history for different IDs, so we can have different HTMLs **/
final int id = params.getInt("id", 0);
if(log != null && log.exists()) {
response.setContentType("text/plain");
long last = log.lastModified();
long len = log.length();
Long position = (Long) request.getSession().getAttribute(SESSION_LAST_POSITION + id);
// init
if(position == null) {
position = Math.max(0, len - MAX_READ);
}
final PrintWriter writer = response.getWriter();
final FileReader reader = new FileReader(log);
if(position > 0) {
reader.skip(position);
}
char[] buffer = new char[1024];
int size;
while((size = reader.read(buffer)) > 0) {
writer.write(buffer, 0, size);
position += size;
}
request.getSession().setAttribute(SESSION_LAST_POSITION + id, position);
reader.close();
} else {
logger.error("Log file not found: " + log);
}
}
| public void process(
final ServletContext context,
final HttpServletRequest request,
final HttpServletResponse response,
final ModuleParam params,
final HashMap<String, FileItem> files) throws IOException {
/** We have different log history for different IDs, so we can have different HTMLs **/
final String id = params.getString("id", "0");
if(log != null && log.exists()) {
response.setContentType("text/plain");
long last = log.lastModified();
long len = log.length();
Long position = (Long) request.getSession().getAttribute(SESSION_LAST_POSITION + id);
// init
if(position == null) {
position = Math.max(0, len - MAX_READ);
}
final PrintWriter writer = response.getWriter();
final FileReader reader = new FileReader(log);
if(position > 0) {
reader.skip(position);
}
char[] buffer = new char[1024];
int size;
while((size = reader.read(buffer)) > 0) {
writer.write(buffer, 0, size);
position += size;
}
request.getSession().setAttribute(SESSION_LAST_POSITION + id, position);
reader.close();
} else {
logger.error("Log file not found: " + log);
}
}
|
diff --git a/src/main/java/pt/go2/application/Server.java b/src/main/java/pt/go2/application/Server.java
index b5c1ba0..eeabb6b 100644
--- a/src/main/java/pt/go2/application/Server.java
+++ b/src/main/java/pt/go2/application/Server.java
@@ -1,242 +1,242 @@
package pt.go2.application;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pt.go2.annotations.Page;
import pt.go2.fileio.Configuration;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
class Server {
private static final Logger LOG = LogManager.getLogger(Server.class);
/**
* Process initial method
*/
public static void main(final String[] args) {
final Configuration config = new Configuration();
LOG.trace("Starting server...");
// log server version
LOG.trace("Preparing to run " + config.VERSION + ".");
LOG.trace("Resuming DB from folder: " + config.DATABASE_FOLDER);
// create listener
LOG.trace("Creating listener.");
final HttpServer http;
try {
http = HttpServer.create(config.HOST, config.BACKLOG);
} catch (IOException e) {
LOG.fatal("Could not create listener.");
return;
}
// Process continues even if Https Listener failed to initialize
HttpsServer https = null;
if (config.HOST_HTTPS != null) {
try {
https = createHttps(config);
} catch (IOException | KeyStoreException | NoSuchAlgorithmException
| CertificateException | UnrecoverableKeyException
| KeyManagementException e) {
LOG.error("Could not create HTTPS listener.", e);
}
}
// Single Threaded Executor
final Executor exec = new Executor() {
@Override
public void execute(Runnable task) {
task.run();
}
};
http.setExecutor(exec);
if (https != null) {
https.setExecutor(exec);
}
LOG.trace("Starting virtual file system.");
BufferedWriter accessLog = null;
try {
// start access log
try {
final FileWriter file = new FileWriter(config.ACCESS_LOG, true);
accessLog = new BufferedWriter(file);
} catch (IOException e) {
System.out.println("Access log redirected to console.");
}
LOG.trace("Appending to access log.");
// RequestHandler
/*
final BasicAuthenticator ba = new BasicAuthenticator("Statistics") {
@Override
public boolean checkCredentials(final String user,
final String pass) {
LOG.info("login: [" + user + "] | [" + pass + "]");
LOG.info("required: [" + config.STATISTICS_USERNAME
+ "] | [" + config.STATISTICS_PASSWORD + "]");
return user.equals(config.STATISTICS_USERNAME)
&& pass.equals(config.STATISTICS_PASSWORD.trim());
}
};
*/
final List<Class<?>> pages = new ArrayList<>();
// scan packages
PageClassLoader.load(config.PAGES_PACKAGES, pages);
final List<Object> pageObjs = new ArrayList<>();
// instantiate objects and inject dependencies
PageClassLoader.injectDependencies(pages, pageObjs);
// create contexts
- final HttpHandler enforcer = new HttpsEnforcer();
+ final HttpHandler enforcer = new HttpsEnforcer(config);
final boolean usingHttps = https != null
&& !"no".equals(config.HTTPS_ENABLED);
for (Class<?> pageClass : pages) {
LOG.info("Creating context for: " + pageClass.getName());
final Page page = pageClass.getAnnotation(Page.class);
if (page == null) {
LOG.info("Missing required Annotations. Skipping");
continue;
}
final HttpHandler handler;
try {
handler = (HttpHandler) pageClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
LOG.info("Class is not a handler.");
continue;
}
if (usingHttps) {
https.createContext(page.path(), handler);
http.createContext(page.path(),
page.requireLogin() ? enforcer : handler);
} else {
https.createContext(page.path(), handler);
}
}
// start server
http.start();
if (https != null) {
http.start();
}
LOG.trace("Listener is Started.");
System.out.println("Server Running. Press [k] to kill listener.");
boolean running = true;
do {
try {
running = System.in.read() == 'k';
} catch (IOException e) {
}
} while (running);
LOG.trace("Server stopping.");
http.stop(1);
if (https != null) {
http.stop(1);
}
} finally {
try {
if (accessLog != null) {
accessLog.close();
}
} catch (IOException e) {
}
LOG.trace("Server stopped.");
}
}
private static HttpsServer createHttps(final Configuration config)
throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException, FileNotFoundException,
UnrecoverableKeyException, KeyManagementException {
HttpsServer https;
final String ksFilename = config.KS_FILENAME;
final char[] ksPassword = config.KS_PASSWORD;
final char[] certPassword = config.CERT_PASSWORD;
final KeyStore ks = KeyStore.getInstance("JKS");
final SSLContext context = SSLContext.getInstance("TLS");
final KeyManagerFactory kmf = KeyManagerFactory
.getInstance("SunX509");
ks.load(new FileInputStream(ksFilename), ksPassword);
kmf.init(ks, certPassword);
context.init(kmf.getKeyManagers(), null, null);
https = HttpsServer.create(config.HOST_HTTPS, config.BACKLOG);
https.setHttpsConfigurator(new HttpsConfigurator(context));
return https;
}
/**
* Private c'tor to forbid instantiation of utility class
*/
private Server() {
}
}
| true | true | public static void main(final String[] args) {
final Configuration config = new Configuration();
LOG.trace("Starting server...");
// log server version
LOG.trace("Preparing to run " + config.VERSION + ".");
LOG.trace("Resuming DB from folder: " + config.DATABASE_FOLDER);
// create listener
LOG.trace("Creating listener.");
final HttpServer http;
try {
http = HttpServer.create(config.HOST, config.BACKLOG);
} catch (IOException e) {
LOG.fatal("Could not create listener.");
return;
}
// Process continues even if Https Listener failed to initialize
HttpsServer https = null;
if (config.HOST_HTTPS != null) {
try {
https = createHttps(config);
} catch (IOException | KeyStoreException | NoSuchAlgorithmException
| CertificateException | UnrecoverableKeyException
| KeyManagementException e) {
LOG.error("Could not create HTTPS listener.", e);
}
}
// Single Threaded Executor
final Executor exec = new Executor() {
@Override
public void execute(Runnable task) {
task.run();
}
};
http.setExecutor(exec);
if (https != null) {
https.setExecutor(exec);
}
LOG.trace("Starting virtual file system.");
BufferedWriter accessLog = null;
try {
// start access log
try {
final FileWriter file = new FileWriter(config.ACCESS_LOG, true);
accessLog = new BufferedWriter(file);
} catch (IOException e) {
System.out.println("Access log redirected to console.");
}
LOG.trace("Appending to access log.");
// RequestHandler
/*
final BasicAuthenticator ba = new BasicAuthenticator("Statistics") {
@Override
public boolean checkCredentials(final String user,
final String pass) {
LOG.info("login: [" + user + "] | [" + pass + "]");
LOG.info("required: [" + config.STATISTICS_USERNAME
+ "] | [" + config.STATISTICS_PASSWORD + "]");
return user.equals(config.STATISTICS_USERNAME)
&& pass.equals(config.STATISTICS_PASSWORD.trim());
}
};
*/
final List<Class<?>> pages = new ArrayList<>();
// scan packages
PageClassLoader.load(config.PAGES_PACKAGES, pages);
final List<Object> pageObjs = new ArrayList<>();
// instantiate objects and inject dependencies
PageClassLoader.injectDependencies(pages, pageObjs);
// create contexts
final HttpHandler enforcer = new HttpsEnforcer();
final boolean usingHttps = https != null
&& !"no".equals(config.HTTPS_ENABLED);
for (Class<?> pageClass : pages) {
LOG.info("Creating context for: " + pageClass.getName());
final Page page = pageClass.getAnnotation(Page.class);
if (page == null) {
LOG.info("Missing required Annotations. Skipping");
continue;
}
final HttpHandler handler;
try {
handler = (HttpHandler) pageClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
LOG.info("Class is not a handler.");
continue;
}
if (usingHttps) {
https.createContext(page.path(), handler);
http.createContext(page.path(),
page.requireLogin() ? enforcer : handler);
} else {
https.createContext(page.path(), handler);
}
}
// start server
http.start();
if (https != null) {
http.start();
}
LOG.trace("Listener is Started.");
System.out.println("Server Running. Press [k] to kill listener.");
boolean running = true;
do {
try {
running = System.in.read() == 'k';
} catch (IOException e) {
}
} while (running);
LOG.trace("Server stopping.");
http.stop(1);
if (https != null) {
http.stop(1);
}
} finally {
try {
if (accessLog != null) {
accessLog.close();
}
} catch (IOException e) {
}
LOG.trace("Server stopped.");
}
}
| public static void main(final String[] args) {
final Configuration config = new Configuration();
LOG.trace("Starting server...");
// log server version
LOG.trace("Preparing to run " + config.VERSION + ".");
LOG.trace("Resuming DB from folder: " + config.DATABASE_FOLDER);
// create listener
LOG.trace("Creating listener.");
final HttpServer http;
try {
http = HttpServer.create(config.HOST, config.BACKLOG);
} catch (IOException e) {
LOG.fatal("Could not create listener.");
return;
}
// Process continues even if Https Listener failed to initialize
HttpsServer https = null;
if (config.HOST_HTTPS != null) {
try {
https = createHttps(config);
} catch (IOException | KeyStoreException | NoSuchAlgorithmException
| CertificateException | UnrecoverableKeyException
| KeyManagementException e) {
LOG.error("Could not create HTTPS listener.", e);
}
}
// Single Threaded Executor
final Executor exec = new Executor() {
@Override
public void execute(Runnable task) {
task.run();
}
};
http.setExecutor(exec);
if (https != null) {
https.setExecutor(exec);
}
LOG.trace("Starting virtual file system.");
BufferedWriter accessLog = null;
try {
// start access log
try {
final FileWriter file = new FileWriter(config.ACCESS_LOG, true);
accessLog = new BufferedWriter(file);
} catch (IOException e) {
System.out.println("Access log redirected to console.");
}
LOG.trace("Appending to access log.");
// RequestHandler
/*
final BasicAuthenticator ba = new BasicAuthenticator("Statistics") {
@Override
public boolean checkCredentials(final String user,
final String pass) {
LOG.info("login: [" + user + "] | [" + pass + "]");
LOG.info("required: [" + config.STATISTICS_USERNAME
+ "] | [" + config.STATISTICS_PASSWORD + "]");
return user.equals(config.STATISTICS_USERNAME)
&& pass.equals(config.STATISTICS_PASSWORD.trim());
}
};
*/
final List<Class<?>> pages = new ArrayList<>();
// scan packages
PageClassLoader.load(config.PAGES_PACKAGES, pages);
final List<Object> pageObjs = new ArrayList<>();
// instantiate objects and inject dependencies
PageClassLoader.injectDependencies(pages, pageObjs);
// create contexts
final HttpHandler enforcer = new HttpsEnforcer(config);
final boolean usingHttps = https != null
&& !"no".equals(config.HTTPS_ENABLED);
for (Class<?> pageClass : pages) {
LOG.info("Creating context for: " + pageClass.getName());
final Page page = pageClass.getAnnotation(Page.class);
if (page == null) {
LOG.info("Missing required Annotations. Skipping");
continue;
}
final HttpHandler handler;
try {
handler = (HttpHandler) pageClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
LOG.info("Class is not a handler.");
continue;
}
if (usingHttps) {
https.createContext(page.path(), handler);
http.createContext(page.path(),
page.requireLogin() ? enforcer : handler);
} else {
https.createContext(page.path(), handler);
}
}
// start server
http.start();
if (https != null) {
http.start();
}
LOG.trace("Listener is Started.");
System.out.println("Server Running. Press [k] to kill listener.");
boolean running = true;
do {
try {
running = System.in.read() == 'k';
} catch (IOException e) {
}
} while (running);
LOG.trace("Server stopping.");
http.stop(1);
if (https != null) {
http.stop(1);
}
} finally {
try {
if (accessLog != null) {
accessLog.close();
}
} catch (IOException e) {
}
LOG.trace("Server stopped.");
}
}
|
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
index b80a82da..e069e291 100644
--- a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
+++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
@@ -1,178 +1,178 @@
package com.redhat.qe.jon.sahi.base.inventory;
import com.redhat.qe.jon.sahi.base.editor.*;
import com.redhat.qe.jon.sahi.tasks.*;
import net.sf.sahi.client.*;
import org.testng.*;
import java.util.*;
import java.util.logging.*;
/**
* represents <b>Operations</b> Tab of given resource.
* Creating instance of this class will navigate to resource and select <b>Operations</b> Tab
*
* @author lzoubek
*/
public class Operations extends ResourceTab {
public Operations(SahiTasks tasks, Resource resource) {
super(tasks, resource);
}
@Override
protected void navigate() {
navigateUnderResource("Operations/Schedules");
raiseErrorIfCellDoesNotExist("Operations");
}
public void history() {
navigateUnderResource("Operations/History");
raiseErrorIfCellDoesNotExist("Operations");
}
/**
* Creates new Operation of given name, also selects it in <b>Operation:</b> combo
*
* @param name of new Operation
* @return new operation
*/
public Operation newOperation(String name) {
tasks.cell("New").click();
tasks.reloadPage();
return new Operation(tasks, name);
}
/**
* asserts operation result, waits until operation is either success or failure.
*
* @param op operation
* @param success if true, success is expected, otherwise failure is expected
* @return result map returned by this operation if operation succeeded, otherwise null.
* In this map, keys are result properties and values are result values
*/
public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().operations().history();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().operations().history();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")));
linkToOperationResults.click();
if (!tasks.cell("Execution ID :").isVisible()) {
log.fine("Operation results not opened correctly");
tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick();
}
tasks.reloadPage();
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest("Header cell: " + el.fetch());
}
- if (headerCells.size() > 1) {
+ if (headerCells.size() > 0) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 2) + " result rows");
log.finest("The rows are: " + rows.toString());
log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
public static class Operation {
private final SahiTasks tasks;
private final String name;
private final Editor editor;
private final Logger log = Logger.getLogger(this.getClass().getName());
public Operation(SahiTasks tasks, String name) {
this.tasks = tasks;
this.name = name;
this.editor = new Editor(tasks);
tasks.waitFor(Timing.WAIT_TIME);
selectOperation(this.name);
}
public void selectOperation(String op) {
getEditor().selectCombo(op);
}
/**
* asserts all required input fields have been filled
*/
public void assertRequiredInputs() {
getEditor().assertRequiredInputs();
}
public Editor getEditor() {
return editor;
}
/**
* clicks <b>Schedule</b> button to start operation
*/
public void schedule() {
tasks.cell("Schedule").click();
Assert.assertTrue(tasks.waitForElementVisible(tasks, tasks.cell("/Operation Schedule created.*/"), "Successful message",Timing.WAIT_TIME)
,"Operation was scheduled");
}
}
}
| true | true | public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().operations().history();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().operations().history();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")));
linkToOperationResults.click();
if (!tasks.cell("Execution ID :").isVisible()) {
log.fine("Operation results not opened correctly");
tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick();
}
tasks.reloadPage();
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest("Header cell: " + el.fetch());
}
if (headerCells.size() > 1) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 2) + " result rows");
log.finest("The rows are: " + rows.toString());
log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
| public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().operations().history();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().operations().history();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")));
linkToOperationResults.click();
if (!tasks.cell("Execution ID :").isVisible()) {
log.fine("Operation results not opened correctly");
tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick();
}
tasks.reloadPage();
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest("Header cell: " + el.fetch());
}
if (headerCells.size() > 0) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 2) + " result rows");
log.finest("The rows are: " + rows.toString());
log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
|
diff --git a/hudson-core/src/main/java/hudson/cli/CreateJobCommand.java b/hudson-core/src/main/java/hudson/cli/CreateJobCommand.java
index 41ded37a..e06d5a9b 100644
--- a/hudson-core/src/main/java/hudson/cli/CreateJobCommand.java
+++ b/hudson-core/src/main/java/hudson/cli/CreateJobCommand.java
@@ -1,63 +1,64 @@
/*******************************************************************************
*
* Copyright (c) 2004-2010, Oracle Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
*
*
*
*******************************************************************************/
package hudson.cli;
import hudson.model.Hudson;
import hudson.Extension;
import static hudson.cli.UpdateJobCommand.ensureJobInTeam;
import static hudson.cli.UpdateJobCommand.validateTeam;
import hudson.model.Item;
import hudson.model.TopLevelItem;
import org.eclipse.hudson.security.team.Team;
import org.kohsuke.args4j.Argument;
/**
* Creates a new job by reading stdin as a configuration XML file.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class CreateJobCommand extends CLICommand {
@Override
public String getShortDescription() {
return "Creates a new job by reading stdin as a configuration XML file";
}
@Argument(metaVar = "NAME", usage = "Name of the job to create. The job name should not be team qualified. Ex: job1.", required = true)
public String name;
@Argument(metaVar = "TEAM", usage = "Team to create the job in. Optional.", index = 1, required = false)
public String team;
protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(name) != null) {
stderr.println("Job '" + name + "' already exists");
return -1;
}
TopLevelItem newItem = h.createProjectFromXML(name, stdin);
+ newItem = h.getItem(newItem.getName());
ensureJobInTeam(newItem, targetTeam, name, stderr);
return 0;
}
}
| true | true | protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(name) != null) {
stderr.println("Job '" + name + "' already exists");
return -1;
}
TopLevelItem newItem = h.createProjectFromXML(name, stdin);
ensureJobInTeam(newItem, targetTeam, name, stderr);
return 0;
}
| protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(name) != null) {
stderr.println("Job '" + name + "' already exists");
return -1;
}
TopLevelItem newItem = h.createProjectFromXML(name, stdin);
newItem = h.getItem(newItem.getName());
ensureJobInTeam(newItem, targetTeam, name, stderr);
return 0;
}
|
diff --git a/core/src/main/java/blast/shell/AlwaysPrototypeScopeResolver.java b/core/src/main/java/blast/shell/AlwaysPrototypeScopeResolver.java
index 2a71f0f..53a3789 100644
--- a/core/src/main/java/blast/shell/AlwaysPrototypeScopeResolver.java
+++ b/core/src/main/java/blast/shell/AlwaysPrototypeScopeResolver.java
@@ -1,19 +1,19 @@
package blast.shell;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;
import org.springframework.context.annotation.ScopedProxyMode;
/**
* Use this for annotation-based command scanners where you always want the commands to be prototypes.
*/
public class AlwaysPrototypeScopeResolver implements ScopeMetadataResolver {
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition beanDefinition) {
ScopeMetadata meta = new ScopeMetadata();
- meta.setScopedProxyMode(ScopedProxyMode.INTERFACES);
+ meta.setScopedProxyMode(ScopedProxyMode.NO);
meta.setScopeName("prototype");
return meta;
}
}
| true | true | public ScopeMetadata resolveScopeMetadata(BeanDefinition beanDefinition) {
ScopeMetadata meta = new ScopeMetadata();
meta.setScopedProxyMode(ScopedProxyMode.INTERFACES);
meta.setScopeName("prototype");
return meta;
}
| public ScopeMetadata resolveScopeMetadata(BeanDefinition beanDefinition) {
ScopeMetadata meta = new ScopeMetadata();
meta.setScopedProxyMode(ScopedProxyMode.NO);
meta.setScopeName("prototype");
return meta;
}
|
diff --git a/src/java/LGDEditTool/Templates/TemplatesEditHistory.java b/src/java/LGDEditTool/Templates/TemplatesEditHistory.java
index 926abe9..a532bed 100644
--- a/src/java/LGDEditTool/Templates/TemplatesEditHistory.java
+++ b/src/java/LGDEditTool/Templates/TemplatesEditHistory.java
@@ -1,110 +1,111 @@
/*
* This file is part of LGDEditTool (LGDET).
*
* LGDET is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* LGDET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LGDET. If not, see <http://www.gnu.org/licenses/>.
*/
package LGDEditTool.Templates;
import java.util.ArrayList;
/**
*
* @author Alexander Richter
*/
public class TemplatesEditHistory {
static ArrayList<String> al = new ArrayList<String>();
/**
* Template for EditHistory.
*/
static public String editHistory() {
+ al.clear();
//insert tablehead
String tableHead = "\t\t\t\t<h2>Edit-History</h2>\n";
tableHead += "\t\t\t\t<table>\n";
tableHead += "\t\t\t\t\t<tr>\n";
tableHead += "\t\t\t\t\t\t<th>time</th>\n";
tableHead += "\t\t\t\t\t\t<th>type</th>\n";
tableHead += "\t\t\t\t\t\t<th>action</th>\n";
tableHead += "\t\t\t\t\t\t<th>comment</th>\n";
tableHead += "\t\t\t\t\t\t<th>user</th>\n";
tableHead += "\t\t\t\t\t\t<th>restore</th>\n";
tableHead += "\t\t\t\t\t\t<th>new comment</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
//insert edithistory from db
searchDB();
//inser table foot
String tableFoot = "\t\t\t\t</table>\n";
al.add(tableFoot);
//array to string for return
String s=new String();
for(int i=0;i<al.size();i++){s+=al.get(i);}
return s;
}
/**
* add arraylist with data
* @param time time
* @param type type
* @param action action
* @param comment comment
* @param user user
*/
static public void fillEditHistoryArray(String time, String type, String action, String comment, String user){
String s = "";
s += "\t\t\t\t\t<tr>\n";
s += "\t\t\t\t\t\t<td>" + time + "</td>\n";
s += "\t\t\t\t\t\t<td>" + type + "</td>\n";
s += "\t\t\t\t\t\t<td>" + action + "</td>\n";
s += "\t\t\t\t\t\t<td>" + comment + "</td>\n";
s += "\t\t\t\t\t\t<td>" + user + "</td>\n";
s += "\t\t\t\t\t\t<td>" + "<a href=\"?tab=history\">restore</a>" + "</td>\n";
s += "\t\t\t\t\t\t<td>" + "<input type=\"text\" name=\"newcomment\" />" + "</td>\n";
s += "\t\t\t\t\t</tr>\n";
al.add(s);
}
/**
* gets edithistory from DB
*/
static public void searchDB(){
//static data only for prototype
String[][] testdata={ { "2012-01-05","k-mapping","edit","wrong","abc"},
{ "2012-01-04","kv-mapping","edit","bla","def"},
{ "2012-01-03","k-mapping","delete","bad","ghi"},
{ "2012-01-02","kv-mapping","delete","wtf","jkl"},
{ "2012-01-01","k-mapping","edit","haha","mno"}
};
for(int i=0;i<5;i++)
{
fillEditHistoryArray(testdata[i][0],testdata[i][1],testdata[i][2],testdata[i]
[3],testdata[i][4]);
}
}
}
| true | true | static public String editHistory() {
//insert tablehead
String tableHead = "\t\t\t\t<h2>Edit-History</h2>\n";
tableHead += "\t\t\t\t<table>\n";
tableHead += "\t\t\t\t\t<tr>\n";
tableHead += "\t\t\t\t\t\t<th>time</th>\n";
tableHead += "\t\t\t\t\t\t<th>type</th>\n";
tableHead += "\t\t\t\t\t\t<th>action</th>\n";
tableHead += "\t\t\t\t\t\t<th>comment</th>\n";
tableHead += "\t\t\t\t\t\t<th>user</th>\n";
tableHead += "\t\t\t\t\t\t<th>restore</th>\n";
tableHead += "\t\t\t\t\t\t<th>new comment</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
//insert edithistory from db
searchDB();
//inser table foot
String tableFoot = "\t\t\t\t</table>\n";
al.add(tableFoot);
//array to string for return
String s=new String();
for(int i=0;i<al.size();i++){s+=al.get(i);}
return s;
}
| static public String editHistory() {
al.clear();
//insert tablehead
String tableHead = "\t\t\t\t<h2>Edit-History</h2>\n";
tableHead += "\t\t\t\t<table>\n";
tableHead += "\t\t\t\t\t<tr>\n";
tableHead += "\t\t\t\t\t\t<th>time</th>\n";
tableHead += "\t\t\t\t\t\t<th>type</th>\n";
tableHead += "\t\t\t\t\t\t<th>action</th>\n";
tableHead += "\t\t\t\t\t\t<th>comment</th>\n";
tableHead += "\t\t\t\t\t\t<th>user</th>\n";
tableHead += "\t\t\t\t\t\t<th>restore</th>\n";
tableHead += "\t\t\t\t\t\t<th>new comment</th>\n";
tableHead += "\t\t\t\t\t</tr>\n";
al.add(tableHead);
//insert edithistory from db
searchDB();
//inser table foot
String tableFoot = "\t\t\t\t</table>\n";
al.add(tableFoot);
//array to string for return
String s=new String();
for(int i=0;i<al.size();i++){s+=al.get(i);}
return s;
}
|
diff --git a/example/com/simontuffs/onejar/example/main/Main.java b/example/com/simontuffs/onejar/example/main/Main.java
index 1327b9a..4fb22ac 100644
--- a/example/com/simontuffs/onejar/example/main/Main.java
+++ b/example/com/simontuffs/onejar/example/main/Main.java
@@ -1,82 +1,87 @@
/*
* Copyright (c) 2004, P. Simon Tuffs ([email protected])
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of P. Simon Tuffs nor the names of any contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.simontuffs.onejar.example.main;
import java.util.Date;
/**
* @author [email protected]
*/
public class Main {
public static void main(String[] args) throws Exception {
System.out.print("Main: " + Main.class.getName() + ".main(");
for (int i=0; i<args.length; i++) {
if (i > 0) System.out.print(" ");
System.out.print(args[i]);
}
System.out.println(")");
Test test = new Test();
long start = new Date().getTime();
test.useUtil();
System.out.println();
try {
test.dumpResource("/main-manifest.mf");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
try {
// Dump a resource relative to this jar file.
test.dumpResource("/duplicate.txt");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
test.loadCodeSource();
System.out.println();
- test.classLoader();
- System.out.println();
+ try {
+ test.classLoader();
+ System.out.println();
+ } catch (Exception x) {
+ System.out.println("Test.classLoader() failed: " + x);
+ System.out.println(" (probably needs a wrapping classloader)");
+ }
long end = new Date().getTime();
System.out.println("Main: finished in " + (end - start) + " ms");
}
}
| true | true | public static void main(String[] args) throws Exception {
System.out.print("Main: " + Main.class.getName() + ".main(");
for (int i=0; i<args.length; i++) {
if (i > 0) System.out.print(" ");
System.out.print(args[i]);
}
System.out.println(")");
Test test = new Test();
long start = new Date().getTime();
test.useUtil();
System.out.println();
try {
test.dumpResource("/main-manifest.mf");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
try {
// Dump a resource relative to this jar file.
test.dumpResource("/duplicate.txt");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
test.loadCodeSource();
System.out.println();
test.classLoader();
System.out.println();
long end = new Date().getTime();
System.out.println("Main: finished in " + (end - start) + " ms");
}
| public static void main(String[] args) throws Exception {
System.out.print("Main: " + Main.class.getName() + ".main(");
for (int i=0; i<args.length; i++) {
if (i > 0) System.out.print(" ");
System.out.print(args[i]);
}
System.out.println(")");
Test test = new Test();
long start = new Date().getTime();
test.useUtil();
System.out.println();
try {
test.dumpResource("/main-manifest.mf");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
try {
// Dump a resource relative to this jar file.
test.dumpResource("/duplicate.txt");
} catch (Exception x) {
System.err.println("test.useResource() failed: " + x);
x.printStackTrace();
}
System.out.println();
test.loadCodeSource();
System.out.println();
try {
test.classLoader();
System.out.println();
} catch (Exception x) {
System.out.println("Test.classLoader() failed: " + x);
System.out.println(" (probably needs a wrapping classloader)");
}
long end = new Date().getTime();
System.out.println("Main: finished in " + (end - start) + " ms");
}
|
diff --git a/src/org/opensolaris/opengrok/index/IndexDatabase.java b/src/org/opensolaris/opengrok/index/IndexDatabase.java
index 181017c7..95c82557 100644
--- a/src/org/opensolaris/opengrok/index/IndexDatabase.java
+++ b/src/org/opensolaris/opengrok/index/IndexDatabase.java
@@ -1,614 +1,615 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.index;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.FSDirectory;
import org.opensolaris.opengrok.analysis.AnalyzerGuru;
import org.opensolaris.opengrok.analysis.FileAnalyzer;
import org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.web.Util;
/**
* This class is used to create / update the index databases. Currently we use
* one index database per project.
*
* @author Trond Norbye
*/
public class IndexDatabase {
private Project project;
private FSDirectory indexDirectory;
private FSDirectory spellDirectory;
private IndexWriter writer;
private IndexReader reader;
private TermEnum uidIter;
private IgnoredNames ignoredNames;
private AnalyzerGuru analyzerGuru;
private File xrefDir;
private boolean interrupted;
private List<IndexChangedListener> listeners;
private File dirtyFile;
private boolean dirty;
/**
* Create a new instance of the Index Database. Use this constructor if
* you don't use any projects
*
* @throws java.io.IOException if an error occurs while creating directories
*/
public IndexDatabase() throws IOException {
initialize();
}
/**
* Create a new instance of an Index Database for a given project
* @param project the project to create the database for
* @throws java.io.IOException if an errror occurs while creating directories
*/
public IndexDatabase(Project project) throws IOException {
this.project = project;
initialize();
}
/**
* Update the index database for all of the projects. Print progress to
* standard out.
* @throws java.lang.Exception if an error occurs
*/
public static void updateAll() throws Exception {
updateAll(null);
}
/**
* Update the index database for all of the projects
* @param listener where to signal the changes to the database
* @throws java.lang.Exception if an error occurs
*/
static void updateAll(IndexChangedListener listener) throws Exception {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.hasProjects()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
if (listener != null) {
db.addIndexChangedListener(listener);
}
db.update();
}
} else {
IndexDatabase db = new IndexDatabase();
if (listener != null) {
db.addIndexChangedListener(listener);
}
db.update();
}
}
private void initialize() throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File indexDir = new File(env.getDataRootFile(), "index");
File spellDir = new File(env.getDataRootFile(), "spellIndex");
if (project != null) {
indexDir = new File(indexDir, project.getPath());
spellDir = new File(spellDir, project.getPath());
}
if (!indexDir.exists() || !spellDir.exists()) {
indexDir.mkdirs();
spellDir.mkdirs();
// to avoid race conditions, just recheck..
if (!indexDir.exists()) {
throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]");
}
if (!spellDir.exists()) {
throw new FileNotFoundException("Failed to create root directory [" + spellDir.getAbsolutePath() + "]");
}
}
indexDirectory = FSDirectory.getDirectory(indexDir);
spellDirectory = FSDirectory.getDirectory(spellDir);
ignoredNames = env.getIgnoredNames();
analyzerGuru = new AnalyzerGuru();
if (RuntimeEnvironment.getInstance().isGenerateHtml()) {
xrefDir = new File(env.getDataRootFile(), "xref");
}
listeners = new ArrayList<IndexChangedListener>();
dirtyFile = new File(indexDir, "dirty");
dirty = dirtyFile.exists();
}
/**
* Update the content of this index database
* @throws java.lang.Exception if an error occurs
*/
public synchronized void update() throws Exception {
interrupted = false;
try {
writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer());
+ writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit());
String root;
File sourceRoot;
if (project != null) {
root = project.getPath();
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), project.getPath());
} else {
root = "";
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
}
String startuid = Util.uid(root, "");
reader = IndexReader.open(indexDirectory); // open existing index
uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
indexDown(sourceRoot, root);
while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
removeFile();
uidIter.next();
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (!interrupted && dirty) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
createSpellingSuggestions();
}
}
/**
* Optimize the index database
*/
public void optimize() {
IndexWriter wrt = null;
try {
if (RuntimeEnvironment.getInstance().isVerbose()) {
System.out.print("Optimizing the index ... ");
}
wrt = new IndexWriter(indexDirectory, null, false);
wrt.optimize();
if (RuntimeEnvironment.getInstance().isVerbose()) {
System.out.println("done");
}
dirtyFile.delete();
dirty = false;
} catch (IOException e) {
System.err.println("ERROR: optimizing index: " + e);
} finally {
if (wrt != null) {
try {
wrt.close();
} catch (IOException e) {
}
}
}
}
/**
* Generate a spelling suggestion for the definitions stored in defs
*/
public void createSpellingSuggestions() {
IndexReader indexReader = null;
SpellChecker checker = null;
try {
if (RuntimeEnvironment.getInstance().isVerbose()) {
System.out.print("Generating spelling suggestion index ... ");
}
indexReader = IndexReader.open(indexDirectory);
checker = new SpellChecker(spellDirectory);
checker.indexDictionary(new LuceneDictionary(indexReader, "defs"));
if (RuntimeEnvironment.getInstance().isVerbose()) {
System.out.println("done");
}
} catch (IOException e) {
System.err.println("ERROR: Generating spelling: " + e);
} finally {
if (indexReader != null) {
try {
indexReader.close();
} catch (IOException e) {
}
}
if (spellDirectory != null) {
spellDirectory.close();
}
}
}
private void setDirty() {
try {
if (!dirty) {
dirtyFile.createNewFile();
dirty = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Remove a stale file (uidIter.term().text()) from the index database
* (and the xref file)
* @throws java.io.IOException if an error occurs
*/
private void removeFile() throws IOException {
String path = Util.uid2url(uidIter.term().text());
for (IndexChangedListener listener : listeners) {
listener.fileRemoved(path);
}
writer.deleteDocuments(uidIter.term());
File xrefFile = new File(xrefDir, path);
xrefFile.delete();
xrefFile.getParentFile().delete();
setDirty();
}
/**
* Add a file to the Lucene index (and generate a xref file)
* @param file The file to add
* @param path The path to the file (from source root)
* @throws java.io.IOException if an error occurs
*/
private void addFile(File file, String path) throws IOException {
InputStream in;
try {
in = new BufferedInputStream(new FileInputStream(file));
} catch (IOException ex) {
System.err.println("Warning: " + ex.getMessage());
return;
}
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path);
for (IndexChangedListener listener : listeners) {
listener.fileAdded(path, fa.getClass().getSimpleName());
}
Document d = analyzerGuru.getDocument(file, in, path, fa);
if (d != null) {
writer.addDocument(d, fa);
Genre g = fa.getFactory().getGenre();
if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) {
File xrefFile = new File(xrefDir, path);
xrefFile.getParentFile().mkdirs();
fa.writeXref(xrefDir, path);
}
setDirty();
} else {
System.err.println("Warning: did not add " + path);
}
try { in.close(); } catch (Exception e) {}
}
/**
* Check if I should accept this file into the index database
* @param file the file to check
* @return true if the file should be included, false otherwise
*/
private boolean accept(File file) {
if (ignoredNames.ignore(file)) {
return false;
}
if (!file.canRead()) {
System.err.println("Warning: could not read " + file.getAbsolutePath());
return false;
}
try {
if (!file.getAbsolutePath().equals(file.getCanonicalPath())) {
System.err.println("Warning: ignored link " + file.getAbsolutePath() +
" -> " + file.getCanonicalPath());
return false;
}
} catch (IOException exp) {
System.err.println("Warning: Failed to resolve name: " + file.getAbsolutePath());
exp.printStackTrace();
}
return true;
}
/**
* Generate indexes recursively
* @param dir the root indexDirectory to generate indexes for
* @param path the path
*/
private void indexDown(File dir, String parent) throws IOException {
if (interrupted) {
return;
}
if (!accept(dir)) {
return;
}
File[] files = dir.listFiles();
if (files == null) {
System.err.println("Failed to get file listing for: " + dir.getAbsolutePath());
return;
}
Arrays.sort(files);
for (File file : files) {
if (accept(file)) {
String path = parent + '/' + file.getName();
if (file.isDirectory()) {
indexDown(file, path);
} else {
if (uidIter != null) {
String uid = Util.uid(path, DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND)); // construct uid for doc
while (uidIter.term() != null && uidIter.term().field().equals("u") &&
uidIter.term().text().compareTo(uid) < 0) {
removeFile();
uidIter.next();
}
if (uidIter.term() != null && uidIter.term().field().equals("u") &&
uidIter.term().text().compareTo(uid) == 0) {
uidIter.next(); // keep matching docs
} else {
addFile(file, path);
}
} else {
addFile(file, path);
}
}
}
}
}
/**
* Interrupt the index generation (and the index generation will stop as
* soon as possible)
*/
public void interrupt() {
interrupted = true;
}
/**
* Register an object to receive events when modifications is done to the
* index database.
*
* @param listener the object to receive the events
*/
void addIndexChangedListener(IndexChangedListener listener) {
listeners.add(listener);
}
/**
* Remove an object from the lists of objects to receive events when
* modifications is done to the index database
*
* @param listener the object to remove
*/
void removeIndexChangedListener(IndexChangedListener listener) {
listeners.remove(listener);
}
/**
* List all files in all of the index databases
* @throws java.lang.Exception if an error occurs
*/
public static void listAllFiles() throws Exception {
listAllFiles(null);
}
/**
* List all files in some of the index databases
* @param subFiles Subdirectories for the various projects to list the files
* for (or null or an empty list to dump all projects)
* @throws java.lang.Exception if an error occurs
*/
public static void listAllFiles(List<String> subFiles) throws Exception {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (!env.hasProjects()) {
IndexDatabase db = new IndexDatabase();
db.listFiles();
} else {
if (subFiles == null || subFiles.isEmpty()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
db.listFiles();
}
} else {
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null) {
System.err.println("Warning: Could not find a project for \"" + path + "\"");
} else {
IndexDatabase db = new IndexDatabase(project);
db.listFiles();
}
}
}
}
}
/**
* List all of the files in this index database
*
* @throws java.lang.Exception if an error occurs
*/
public void listFiles() throws Exception {
IndexReader ireader = null;
TermEnum iter = null;
try {
ireader = IndexReader.open(indexDirectory); // open existing index
iter = ireader.terms(new Term("u", "")); // init uid iterator
while (iter.term() != null) {
System.out.println(Util.uid2url(iter.term().text()));
iter.next();
}
} finally {
if (iter != null) {
try {
iter.close();
} catch (Exception e) {
}
}
if (ireader != null) {
try {
ireader.close();
} catch (Exception e) {
}
}
}
}
static void listFrequentTokens() throws Exception {
listFrequentTokens(null);
}
static void listFrequentTokens(ArrayList<String> subFiles) throws Exception {
final int limit = 4;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (!env.hasProjects()) {
IndexDatabase db = new IndexDatabase();
db.listTokens(limit);
} else {
if (subFiles == null || subFiles.isEmpty()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
} else {
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null) {
System.err.println("Warning: Could not find a project for \"" + path + "\"");
} else {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
}
}
}
}
public void listTokens(int freq) throws Exception {
IndexReader ireader = null;
TermEnum iter = null;
try {
ireader = IndexReader.open(indexDirectory);
iter = ireader.terms(new Term("defs", ""));
while (iter.term() != null) {
if (iter.term().field().startsWith("f")) {
if (iter.docFreq() > 16 && iter.term().text().length() > freq) {
System.out.println(iter.term().text());
}
iter.next();
} else {
break;
}
}
} finally {
if (iter != null) {
try {
iter.close();
} catch (Exception e) {
}
}
if (ireader != null) {
try {
ireader.close();
} catch (Exception e) {
}
}
}
}
/**
* Get an indexReader for the Index database where a given file
* @param path the file to get the database for
* @return The index database where the file should be located or null if
* it cannot be located.
*/
public static IndexReader getIndexReader(String path) {
IndexReader ret = null;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File indexDir = new File(env.getDataRootFile(), "index");
if (env.hasProjects()) {
Project p = Project.getProject(path);
if (p != null) {
indexDir = new File(indexDir, p.getPath());
} else {
return null;
}
}
if (indexDir.exists() && IndexReader.indexExists(indexDir)) {
try {
ret = IndexReader.open(indexDir);
} catch (Exception ex) {
System.err.println("Failed to open index: " + indexDir.getAbsolutePath());
ex.printStackTrace();
}
}
return ret;
}
}
| true | true | public synchronized void update() throws Exception {
interrupted = false;
try {
writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer());
String root;
File sourceRoot;
if (project != null) {
root = project.getPath();
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), project.getPath());
} else {
root = "";
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
}
String startuid = Util.uid(root, "");
reader = IndexReader.open(indexDirectory); // open existing index
uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
indexDown(sourceRoot, root);
while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
removeFile();
uidIter.next();
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (!interrupted && dirty) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
createSpellingSuggestions();
}
}
| public synchronized void update() throws Exception {
interrupted = false;
try {
writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer());
writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit());
String root;
File sourceRoot;
if (project != null) {
root = project.getPath();
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), project.getPath());
} else {
root = "";
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
}
String startuid = Util.uid(root, "");
reader = IndexReader.open(indexDirectory); // open existing index
uidIter = reader.terms(new Term("u", startuid)); // init uid iterator
indexDown(sourceRoot, root);
while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) {
removeFile();
uidIter.next();
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (!interrupted && dirty) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
createSpellingSuggestions();
}
}
|
diff --git a/luciddb/src/com/lucidera/luciddb/applib/cursor/CollapseRowsUdx.java b/luciddb/src/com/lucidera/luciddb/applib/cursor/CollapseRowsUdx.java
index 3cb1685bf..374729515 100644
--- a/luciddb/src/com/lucidera/luciddb/applib/cursor/CollapseRowsUdx.java
+++ b/luciddb/src/com/lucidera/luciddb/applib/cursor/CollapseRowsUdx.java
@@ -1,113 +1,120 @@
/*
// $Id$
// LucidDB is a DBMS optimized for business intelligence.
// Copyright (C) 2006-2007 LucidEra, Inc.
// Copyright (C) 2006-2007 The Eigenbase Project
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.lucidera.luciddb.applib.cursor;
import java.sql.*;
import java.util.*;
import com.lucidera.luciddb.applib.resource.*;
/**
* Collapses one to many relationships into one to one relationships. In the
* case where A maps to B, this will result in A mapping to a concatenation
* of all Bs which previously mapped to A.
*
* @author Elizabeth Lin
* @version $Id$
*/
public abstract class CollapseRowsUdx
{
public static void execute(
ResultSet inputSet, String delimiter, PreparedStatement resultInserter)
throws ApplibException
{
// validate the number of input and output columns
try{
if ((resultInserter.getParameterMetaData().getParameterCount()
!= 3) || (inputSet.getMetaData().getColumnCount() != 2))
{
throw ApplibResourceObject.get().InputOutputColumnError.ex();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().CannotGetMetaData.ex(e);
}
HashMap<String, ArrayList<String>> relMap = new HashMap();
ArrayList currentList;
String currentKey;
String currentValue;
try {
while (inputSet.next()) {
currentKey = inputSet.getString(1);
currentValue = inputSet.getString(2);
currentList = relMap.get(currentKey);
// create list if none exists
if (currentList == null) {
currentList = new ArrayList();
}
// add value to list unless it's a null
if (currentValue != null) {
currentList.add(currentValue);
}
relMap.put(currentKey, currentList);
}
// output table
Iterator<String> keyIter = relMap.keySet().iterator();
while (keyIter.hasNext()) {
currentKey = keyIter.next();
resultInserter.setString(1, currentKey);
currentList = relMap.get(currentKey);
if ((currentList == null) || currentList.isEmpty()) {
// inserts null for the concatenation if list doesn't
// exist or is empty
resultInserter.setString(2, null);
resultInserter.setInt(3, 0);
} else {
// inserts concatenation of all items in list
Iterator<String> valIter = currentList.iterator();
String concatenation = valIter.next();
int numItems = 1;
while (valIter.hasNext()) {
concatenation = concatenation + delimiter +
valIter.next();
numItems++;
}
- resultInserter.setString(2, concatenation);
- resultInserter.setInt(3, numItems);
+ // oversize values are likely to cause trouble downstream,
+ // so treat them as empty list
+ if (concatenation.length() > 16384) {
+ resultInserter.setString(2, null);
+ resultInserter.setInt(3, 0);
+ } else {
+ resultInserter.setString(2, concatenation);
+ resultInserter.setInt(3, numItems);
+ }
}
resultInserter.executeUpdate();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().DatabaseAccessError.ex(
e.toString(), e);
}
}
}
// End CollapseOneToManyRelationshipsUdx.java
| true | true | public static void execute(
ResultSet inputSet, String delimiter, PreparedStatement resultInserter)
throws ApplibException
{
// validate the number of input and output columns
try{
if ((resultInserter.getParameterMetaData().getParameterCount()
!= 3) || (inputSet.getMetaData().getColumnCount() != 2))
{
throw ApplibResourceObject.get().InputOutputColumnError.ex();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().CannotGetMetaData.ex(e);
}
HashMap<String, ArrayList<String>> relMap = new HashMap();
ArrayList currentList;
String currentKey;
String currentValue;
try {
while (inputSet.next()) {
currentKey = inputSet.getString(1);
currentValue = inputSet.getString(2);
currentList = relMap.get(currentKey);
// create list if none exists
if (currentList == null) {
currentList = new ArrayList();
}
// add value to list unless it's a null
if (currentValue != null) {
currentList.add(currentValue);
}
relMap.put(currentKey, currentList);
}
// output table
Iterator<String> keyIter = relMap.keySet().iterator();
while (keyIter.hasNext()) {
currentKey = keyIter.next();
resultInserter.setString(1, currentKey);
currentList = relMap.get(currentKey);
if ((currentList == null) || currentList.isEmpty()) {
// inserts null for the concatenation if list doesn't
// exist or is empty
resultInserter.setString(2, null);
resultInserter.setInt(3, 0);
} else {
// inserts concatenation of all items in list
Iterator<String> valIter = currentList.iterator();
String concatenation = valIter.next();
int numItems = 1;
while (valIter.hasNext()) {
concatenation = concatenation + delimiter +
valIter.next();
numItems++;
}
resultInserter.setString(2, concatenation);
resultInserter.setInt(3, numItems);
}
resultInserter.executeUpdate();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().DatabaseAccessError.ex(
e.toString(), e);
}
}
| public static void execute(
ResultSet inputSet, String delimiter, PreparedStatement resultInserter)
throws ApplibException
{
// validate the number of input and output columns
try{
if ((resultInserter.getParameterMetaData().getParameterCount()
!= 3) || (inputSet.getMetaData().getColumnCount() != 2))
{
throw ApplibResourceObject.get().InputOutputColumnError.ex();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().CannotGetMetaData.ex(e);
}
HashMap<String, ArrayList<String>> relMap = new HashMap();
ArrayList currentList;
String currentKey;
String currentValue;
try {
while (inputSet.next()) {
currentKey = inputSet.getString(1);
currentValue = inputSet.getString(2);
currentList = relMap.get(currentKey);
// create list if none exists
if (currentList == null) {
currentList = new ArrayList();
}
// add value to list unless it's a null
if (currentValue != null) {
currentList.add(currentValue);
}
relMap.put(currentKey, currentList);
}
// output table
Iterator<String> keyIter = relMap.keySet().iterator();
while (keyIter.hasNext()) {
currentKey = keyIter.next();
resultInserter.setString(1, currentKey);
currentList = relMap.get(currentKey);
if ((currentList == null) || currentList.isEmpty()) {
// inserts null for the concatenation if list doesn't
// exist or is empty
resultInserter.setString(2, null);
resultInserter.setInt(3, 0);
} else {
// inserts concatenation of all items in list
Iterator<String> valIter = currentList.iterator();
String concatenation = valIter.next();
int numItems = 1;
while (valIter.hasNext()) {
concatenation = concatenation + delimiter +
valIter.next();
numItems++;
}
// oversize values are likely to cause trouble downstream,
// so treat them as empty list
if (concatenation.length() > 16384) {
resultInserter.setString(2, null);
resultInserter.setInt(3, 0);
} else {
resultInserter.setString(2, concatenation);
resultInserter.setInt(3, numItems);
}
}
resultInserter.executeUpdate();
}
} catch (SQLException e) {
throw ApplibResourceObject.get().DatabaseAccessError.ex(
e.toString(), e);
}
}
|
diff --git a/tabix/src/org/broad/tabix/TabixReader.java b/tabix/src/org/broad/tabix/TabixReader.java
index 382e4382..490f39e0 100644
--- a/tabix/src/org/broad/tabix/TabixReader.java
+++ b/tabix/src/org/broad/tabix/TabixReader.java
@@ -1,429 +1,429 @@
/* The MIT License
Copyright (c) 2010 Broad Institute.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* Contact: Heng Li <[email protected]> */
package org.broad.tabix;
import java.io.*;
import java.nio.*;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Set;
import net.sf.samtools.util.BlockCompressedInputStream;
import net.sf.samtools.util.SeekableStream;
public class TabixReader {
private BlockCompressedInputStream mFp;
protected int mPreset;
protected int mSc;
protected int mBc;
protected int mEc;
protected int mMeta;
protected int mSkip;
protected String[] mSeq;
protected HashMap<String, Integer> mChr2tid;
private static int MAX_BIN = 37450;
private static int TAD_MIN_CHUNK_GAP = 32768;
protected static int TAD_LIDX_SHIFT = 14;
protected class TPair64 implements Comparable<TPair64> {
long u, v;
public TPair64(final long _u, final long _v) {
u = _u; v = _v;
}
public TPair64(final TPair64 p) {
u = p.u; v = p.v;
}
public int compareTo(final TPair64 p) {
return u == p.u? 0 : ((u < p.u) ^ (u < 0) ^ (p.u < 0))? -1 : 1; // unsigned 64-bit comparison
}
};
protected class TIndex {
HashMap<Integer, TPair64[]> b; // binning index
long[] l; // linear index
};
private TIndex[] mIndex;
protected class TIntv {
int tid, beg, end, bin;
};
private static boolean less64(final long u, final long v) { // unsigned 64-bit comparison
return (u < v) ^ (u < 0) ^ (v < 0);
}
/**
* The constructor
*
* @param fn File name of the data file
*/
public TabixReader(final String fn) throws IOException {
mFp = new BlockCompressedInputStream(new File(fn));
File indexFile = new File(fn + ".tbi");
if (indexFile.exists()) {
readIndex(indexFile);
}
}
public TabixReader(SeekableStream baseStream, final File index) throws IOException {
mFp = new BlockCompressedInputStream(baseStream);
readIndex(index);
}
private static int reg2bins(final int beg, final int _end, final int[] list) {
int i = 0, k, end = _end;
if (beg >= end) return 0;
if (end >= 1<<29) end = 1<<29;
--end;
list[i++] = 0;
for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) list[i++] = k;
for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) list[i++] = k;
for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) list[i++] = k;
for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) list[i++] = k;
for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) list[i++] = k;
return i;
}
public static int readInt(final InputStream is) throws IOException {
byte[] buf = new byte[4];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static long readLong(final InputStream is) throws IOException {
byte[] buf = new byte[8];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
public static String readLine(final InputStream is) throws IOException {
StringBuilder buf = new StringBuilder();
int c;
while ((c = is.read()) >= 0 && c != '\n')
buf.append((char)c);
if (c < 0) return null;
return buf.toString();
}
/**
* Read the Tabix index from a file
*
* @param fp File pointer
*/
public final void readIndex(final File fp) throws IOException {
if (fp == null) return;
BlockCompressedInputStream is = new BlockCompressedInputStream(fp);
byte[] buf = new byte[4];
is.read(buf, 0, 4); // read "TBI\1"
mSeq = new String[readInt(is)]; // # sequences
mChr2tid = new HashMap<String, Integer>();
mPreset = readInt(is);
mSc = readInt(is);
mBc = readInt(is);
mEc = readInt(is);
mMeta = readInt(is);
mSkip = readInt(is);
// read sequence dictionary
int i, j, k, l = readInt(is);
buf = new byte[l];
is.read(buf);
for (i = j = k = 0; i < buf.length; ++i) {
if (buf[i] == 0) {
byte[] b = new byte[i - j];
System.arraycopy(buf, j, b, 0, b.length);
String s = homogenizeSequence(new String(b));
mChr2tid.put(s, k);
mSeq[k++] = s;
j = i + 1;
}
}
// read the index
mIndex = new TIndex[mSeq.length];
for (i = 0; i < mSeq.length; ++i) {
// the binning index
int n_bin = readInt(is);
mIndex[i] = new TIndex();
mIndex[i].b = new HashMap<Integer, TPair64[]>();
for (j = 0; j < n_bin; ++j) {
int bin = readInt(is);
TPair64[] chunks = new TPair64[readInt(is)];
for (k = 0; k < chunks.length; ++k) {
long u = readLong(is);
long v = readLong(is);
chunks[k] = new TPair64(u, v); // in C, this is inefficient
}
mIndex[i].b.put(bin, chunks);
}
// the linear index
mIndex[i].l = new long[readInt(is)];
for (k = 0; k < mIndex[i].l.length; ++k)
mIndex[i].l[k] = readLong(is);
}
// close
is.close();
}
/**
* Read one line from the data file.
*/
public String readLine() throws IOException {
return readLine(mFp);
}
protected int chr2tid(String chr) {
chr = homogenizeSequence(chr);
if (mChr2tid.containsKey(chr)) {
return mChr2tid.get(chr);
}
return -1;
}
/**
* Parse a region in the format of "chr1", "chr1:100" or "chr1:100-1000"
*
* @param reg Region string
* @return An array where the three elements are sequence_id,
* region_begin and region_end. On failure, sequence_id==-1.
*/
public int[] parseReg(final String reg) { // FIXME: NOT working when the sequence name contains : or -.
int colon, hyphen;
int[] ret = new int[3];
colon = reg.indexOf(':'); hyphen = reg.indexOf('-');
String chr = colon >= 0? reg.substring(0, colon) : reg;
ret[1] = colon >= 0? Integer.parseInt(reg.substring(colon+1, hyphen >= 0? hyphen : reg.length())) - 1 : 0;
ret[2] = hyphen >= 0? Integer.parseInt(reg.substring(hyphen+1)) : 0x7fffffff;
ret[0] = chr2tid(chr);
return ret;
}
protected TIntv getIntv(final String s) {
TIntv intv = new TIntv();
int col = 0, end = 0, beg = 0;
while ((end = s.indexOf('\t', beg)) >= 0 || end == -1) {
++col;
if (col == mSc) {
- intv.tid = chr2tid(s.substring(beg, end));
+ intv.tid = chr2tid(end != -1 ? s.substring(beg, end) : s.substring(beg));
} else if (col == mBc) {
- intv.beg = intv.end = Integer.parseInt(s.substring(beg, end));
+ intv.beg = intv.end = Integer.parseInt(end != -1 ? s.substring(beg, end) : s.substring(beg));
if ((mPreset&0x10000) != 0) ++intv.end;
else --intv.beg;
if (intv.beg < 0) intv.beg = 0;
if (intv.end < 1) intv.end = 1;
} else { // FIXME: SAM supports are not tested yet
if ((mPreset&0xffff) == 0) { // generic
if (col == mEc)
- intv.end = Integer.parseInt(s.substring(beg, end));
+ intv.end = Integer.parseInt(end != -1 ? s.substring(beg, end) : s.substring(beg));
} else if ((mPreset&0xffff) == 1) { // SAM
if (col == 6) { // CIGAR
int l = 0, i, j;
String cigar = s.substring(beg, end);
for (i = j = 0; i < cigar.length(); ++i) {
if (cigar.charAt(i) > '9') {
int op = cigar.charAt(i);
if (op == 'M' || op == 'D' || op == 'N')
l += Integer.parseInt(cigar.substring(j, i));
}
}
intv.end = intv.beg + l;
}
} else if ((mPreset&0xffff) == 2) { // VCF
String alt;
alt = end >= 0? s.substring(beg, end) : s.substring(beg);
if (col == 4) { // REF
if (alt.length() > 0) intv.end = intv.beg + alt.length();
} else if (col == 8) { // INFO
int e_off = -1, i = alt.indexOf("END=");
if (i == 0) e_off = 4;
else if (i > 0) {
i = alt.indexOf(";END=");
if (i >= 0) e_off = i + 5;
}
if (e_off > 0) {
i = alt.indexOf(";", e_off);
intv.end = Integer.parseInt(i > e_off? alt.substring(e_off, i) : alt.substring(e_off));
}
}
}
}
if (end == -1) break;
beg = end + 1;
}
return intv;
}
public Set<String> getReferenceNames() {
return mChr2tid.keySet();
}
/**
* Index of column which contains chromosome information (zero-based).
*/
public int getChromColumn() {
return mSc - 1;
}
/**
* Index of column which contains start positions (zero-based).
*/
public int getStartColumn() {
return mBc - 1;
}
/**
* Index of column which contains end positions (zero-based).
*/
public int getEndColumn() {
return mEc - 1;
}
public char getCommentChar() {
return (char)mMeta;
}
public class Iterator {
private int i, n_seeks;
private int tid, beg, end;
private TPair64[] off;
private long curr_off;
private boolean iseof;
Iterator(final int _tid, final int _beg, final int _end, final TPair64[] _off) {
i = -1; n_seeks = 0; curr_off = 0; iseof = false;
off = _off; tid = _tid; beg = _beg; end = _end;
}
public String next() throws IOException {
if (iseof) return null;
for (;;) {
if (curr_off == 0 || !less64(curr_off, off[i].v)) { // then jump to the next chunk
if (i == off.length - 1) break; // no more chunks
if (i >= 0) assert(curr_off == off[i].v); // otherwise bug
if (i < 0 || off[i].v != off[i+1].u) { // not adjacent chunks; then seek
mFp.seek(off[i+1].u);
curr_off = mFp.getFilePointer();
++n_seeks;
}
++i;
}
String s;
if ((s = readLine(mFp)) != null) {
TIntv intv;
char[] str = s.toCharArray();
curr_off = mFp.getFilePointer();
if (str.length == 0 || str[0] == mMeta) continue;
intv = getIntv(s);
if (intv.tid != tid || intv.beg >= end) break; // no need to proceed
else if (intv.end > beg && intv.beg < end) return s; // overlap; return
} else break; // end of file
}
iseof = true;
return null;
}
};
public Iterator query(final int tid, final int beg, final int end) {
TPair64[] off, chunks;
long min_off;
TIndex idx = mIndex[tid];
int[] bins = new int[MAX_BIN];
int i, l, n_off, n_bins = reg2bins(beg, end, bins);
if (idx.l.length > 0)
min_off = (beg>>TAD_LIDX_SHIFT >= idx.l.length)? idx.l[idx.l.length-1] : idx.l[beg>>TAD_LIDX_SHIFT];
else min_off = 0;
for (i = n_off = 0; i < n_bins; ++i) {
if ((chunks = idx.b.get(bins[i])) != null)
n_off += chunks.length;
}
if (n_off == 0) return null;
off = new TPair64[n_off];
for (i = n_off = 0; i < n_bins; ++i)
if ((chunks = idx.b.get(bins[i])) != null)
for (int j = 0; j < chunks.length; ++j)
if (less64(min_off, chunks[j].v))
off[n_off++] = new TPair64(chunks[j]);
if (n_off == 0) return null;
Arrays.sort(off, 0, n_off);
// resolve completely contained adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (less64(off[l].v, off[i].v)) {
++l;
off[l].u = off[i].u; off[l].v = off[i].v;
}
}
n_off = l + 1;
// resolve overlaps between adjacent blocks; this may happen due to the merge in indexing
for (i = 1; i < n_off; ++i)
if (!less64(off[i-1].v, off[i].u)) off[i-1].v = off[i].u;
// merge adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (off[l].v>>16 == off[i].u>>16) off[l].v = off[i].v;
else {
++l;
off[l].u = off[i].u;
off[l].v = off[i].v;
}
}
n_off = l + 1;
// return
TPair64[] ret = new TPair64[n_off];
for (i = 0; i < n_off; ++i) ret[i] = new TPair64(off[i].u, off[i].v); // in C, this is inefficient
return new TabixReader.Iterator(tid, beg, end, ret);
}
public Iterator query(final String reg) {
int[] x = parseReg(reg);
return query(x[0], x[1], x[2]);
}
/**
* Return string without sequence title (chr, contig)
*/
private static String homogenizeSequence(String s){
String result = s;
if(result.contains("chr")){
result = result.replaceAll("chr", "");
}
if(result.contains("Chr")){
result = result.replaceAll("Chr", "");
}
if(result.contains("contig")){
result = result.replaceAll("contig", "");
}
if(result.contains("Contig")){
result = result.replaceAll("Contig", "");
}
return result;
}
}
| false | true | protected TIntv getIntv(final String s) {
TIntv intv = new TIntv();
int col = 0, end = 0, beg = 0;
while ((end = s.indexOf('\t', beg)) >= 0 || end == -1) {
++col;
if (col == mSc) {
intv.tid = chr2tid(s.substring(beg, end));
} else if (col == mBc) {
intv.beg = intv.end = Integer.parseInt(s.substring(beg, end));
if ((mPreset&0x10000) != 0) ++intv.end;
else --intv.beg;
if (intv.beg < 0) intv.beg = 0;
if (intv.end < 1) intv.end = 1;
} else { // FIXME: SAM supports are not tested yet
if ((mPreset&0xffff) == 0) { // generic
if (col == mEc)
intv.end = Integer.parseInt(s.substring(beg, end));
} else if ((mPreset&0xffff) == 1) { // SAM
if (col == 6) { // CIGAR
int l = 0, i, j;
String cigar = s.substring(beg, end);
for (i = j = 0; i < cigar.length(); ++i) {
if (cigar.charAt(i) > '9') {
int op = cigar.charAt(i);
if (op == 'M' || op == 'D' || op == 'N')
l += Integer.parseInt(cigar.substring(j, i));
}
}
intv.end = intv.beg + l;
}
} else if ((mPreset&0xffff) == 2) { // VCF
String alt;
alt = end >= 0? s.substring(beg, end) : s.substring(beg);
if (col == 4) { // REF
if (alt.length() > 0) intv.end = intv.beg + alt.length();
} else if (col == 8) { // INFO
int e_off = -1, i = alt.indexOf("END=");
if (i == 0) e_off = 4;
else if (i > 0) {
i = alt.indexOf(";END=");
if (i >= 0) e_off = i + 5;
}
if (e_off > 0) {
i = alt.indexOf(";", e_off);
intv.end = Integer.parseInt(i > e_off? alt.substring(e_off, i) : alt.substring(e_off));
}
}
}
}
if (end == -1) break;
beg = end + 1;
}
return intv;
}
| protected TIntv getIntv(final String s) {
TIntv intv = new TIntv();
int col = 0, end = 0, beg = 0;
while ((end = s.indexOf('\t', beg)) >= 0 || end == -1) {
++col;
if (col == mSc) {
intv.tid = chr2tid(end != -1 ? s.substring(beg, end) : s.substring(beg));
} else if (col == mBc) {
intv.beg = intv.end = Integer.parseInt(end != -1 ? s.substring(beg, end) : s.substring(beg));
if ((mPreset&0x10000) != 0) ++intv.end;
else --intv.beg;
if (intv.beg < 0) intv.beg = 0;
if (intv.end < 1) intv.end = 1;
} else { // FIXME: SAM supports are not tested yet
if ((mPreset&0xffff) == 0) { // generic
if (col == mEc)
intv.end = Integer.parseInt(end != -1 ? s.substring(beg, end) : s.substring(beg));
} else if ((mPreset&0xffff) == 1) { // SAM
if (col == 6) { // CIGAR
int l = 0, i, j;
String cigar = s.substring(beg, end);
for (i = j = 0; i < cigar.length(); ++i) {
if (cigar.charAt(i) > '9') {
int op = cigar.charAt(i);
if (op == 'M' || op == 'D' || op == 'N')
l += Integer.parseInt(cigar.substring(j, i));
}
}
intv.end = intv.beg + l;
}
} else if ((mPreset&0xffff) == 2) { // VCF
String alt;
alt = end >= 0? s.substring(beg, end) : s.substring(beg);
if (col == 4) { // REF
if (alt.length() > 0) intv.end = intv.beg + alt.length();
} else if (col == 8) { // INFO
int e_off = -1, i = alt.indexOf("END=");
if (i == 0) e_off = 4;
else if (i > 0) {
i = alt.indexOf(";END=");
if (i >= 0) e_off = i + 5;
}
if (e_off > 0) {
i = alt.indexOf(";", e_off);
intv.end = Integer.parseInt(i > e_off? alt.substring(e_off, i) : alt.substring(e_off));
}
}
}
}
if (end == -1) break;
beg = end + 1;
}
return intv;
}
|
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFConsole.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFConsole.java
index 097187c41..29132839d 100644
--- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFConsole.java
+++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFConsole.java
@@ -1,424 +1,435 @@
/*******************************************************************************
* Copyright (c) 2007, 2013 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.ui.model;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.tcf.internal.debug.model.TCFLaunch;
import org.eclipse.tcf.internal.debug.ui.Activator;
import org.eclipse.tcf.internal.debug.ui.ImageCache;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IErrorReport;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IProcessesV1;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.util.TCFDataCache;
import org.eclipse.tm.internal.terminal.control.ITerminalListener;
import org.eclipse.tm.internal.terminal.control.ITerminalViewControl;
import org.eclipse.tm.internal.terminal.control.TerminalViewControlFactory;
import org.eclipse.tm.internal.terminal.provisional.api.ISettingsPage;
import org.eclipse.tm.internal.terminal.provisional.api.ISettingsStore;
import org.eclipse.tm.internal.terminal.provisional.api.ITerminalConnector;
import org.eclipse.tm.internal.terminal.provisional.api.ITerminalControl;
import org.eclipse.tm.internal.terminal.provisional.api.TerminalState;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.AbstractConsole;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.part.IPageBookViewPage;
import org.eclipse.ui.part.Page;
@SuppressWarnings("restriction")
class TCFConsole extends AbstractConsole {
public static final int
TYPE_PROCESS_CONSOLE = 1,
TYPE_PROCESS_TERMINAL = 2,
TYPE_UART_TERMINAL = 3,
TYPE_CMD_LINE = 4,
TYPE_DPRINTF = 5;
private static int page_id_cnt = 0;
private final TCFModel model;
private final Display display;
private final String ctx_id;
private final int type;
private final LinkedList<ViewPage> pages = new LinkedList<ViewPage>();
private final LinkedList<Message> history = new LinkedList<Message>();
private static class Message {
int stream_id;
byte[] data;
}
private class ViewPage extends Page implements ITerminalConnector, ITerminalListener {
private final String page_id = "Page-" + page_id_cnt++;
private final LinkedList<Message> inp_queue = new LinkedList<Message>();
private final OutputStream out_stream = new OutputStream() {
@Override
public void write(final int b) throws IOException {
if (ctx_id == null) return;
Protocol.invokeAndWait(new Runnable() {
public void run() {
try {
String s = "" + (char)b;
byte[] buf = s.getBytes("UTF8");
model.getLaunch().writeProcessInputStream(ctx_id, buf, 0, buf.length);
}
catch (Exception x) {
model.onProcessStreamError(ctx_id, 0, x, 0);
}
}
});
}
};
private ITerminalViewControl view_control;
private OutputStream rtt;
private int ws_col;
private int ws_row;
private final Thread inp_thread = new Thread() {
public void run() {
try {
for (;;) {
Message m = null;
synchronized (inp_queue) {
while (inp_queue.size() == 0) inp_queue.wait();
m = inp_queue.removeFirst();
}
if (m.data == null) break;
if (type == TYPE_PROCESS_CONSOLE) {
String s = "\u001b[30m";
switch (m.stream_id) {
case 1: s = "\u001b[31m"; break;
case 2: s = "\u001b[34m"; break;
case 3: s = "\u001b[32m"; break;
}
rtt.write(s.getBytes("UTF8"));
for (int i = 0; i < m.data.length; i++) {
int ch = m.data[i] & 0xff;
if (ch == '\n') rtt.write('\r');
rtt.write(ch);
}
}
+ else if (type == TYPE_DPRINTF) {
+ int i = 0;
+ for (int j = 0; j < m.data.length; j++) {
+ if (m.data[j] == '\n') {
+ rtt.write(m.data, i, j - i);
+ rtt.write('\r');
+ i = j;
+ }
+ }
+ rtt.write(m.data, i, m.data.length - i);
+ }
else {
rtt.write(m.data);
}
}
}
catch (Throwable x) {
Activator.log("Cannot write console output", x);
}
}
};
@Override
public void createControl(Composite parent) {
assert view_control == null;
view_control = TerminalViewControlFactory.makeControl(this, parent, null);
view_control.setConnector(this);
view_control.connectTerminal();
}
@Override
public void dispose() {
if (view_control != null) {
// TODO: need a way to stop terminal update timer, see PollingTextCanvasModel
// It the timer is not stopped, it causes memory leak
view_control.disposeTerminal();
view_control.setConnector(null);
view_control = null;
}
}
@Override
public Control getControl() {
return view_control.getRootControl();
}
@Override
public void setActionBars(IActionBars actionBars) {
}
@Override
public void setFocus() {
view_control.setFocus();
}
@Override
@SuppressWarnings("rawtypes")
public Object getAdapter(Class adapter) {
return null;
}
@Override
public void setTerminalSize(final int w, final int h) {
if (ws_col == w && ws_row == h) return;
ws_col = w;
ws_row = h;
if (type != TYPE_PROCESS_TERMINAL) return;
Protocol.invokeLater(new Runnable() {
@Override
public void run() {
final TCFLaunch launch = model.getLaunch();
if (launch.isProcessExited()) return;
final IChannel channel = launch.getChannel();
if (channel.getState() != IChannel.STATE_OPEN) return;
IProcessesV1 prs = channel.getRemoteService(IProcessesV1.class);
if (prs == null) return;
prs.setWinSize(ctx_id, w, h, new IProcessesV1.DoneCommand() {
@Override
public void doneCommand(IToken token, Exception error) {
if (error == null) return;
if (launch.isProcessExited()) return;
if (channel.getState() != IChannel.STATE_OPEN) return;
if (error instanceof IErrorReport && ((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) return;
Activator.log("Cannot set process TTY window size", error);
}
});
}
});
}
@Override
public void save(ISettingsStore store) {
}
@Override
public ISettingsPage makeSettingsPage() {
return null;
}
@Override
public void load(ISettingsStore store) {
}
@Override
public boolean isLocalEcho() {
return false;
}
@Override
public boolean isInitialized() {
return true;
}
@Override
public boolean isHidden() {
return false;
}
@Override
public OutputStream getTerminalToRemoteStream() {
return out_stream;
}
@Override
public String getSettingsSummary() {
return null;
}
@Override
public String getName() {
return TCFConsole.this.getName();
}
@Override
public String getInitializationErrorMessage() {
return null;
}
@Override
public String getId() {
return page_id;
}
@Override
public void disconnect() {
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
pages.remove(ViewPage.this);
synchronized (inp_queue) {
inp_queue.add(new Message());
inp_queue.notify();
}
}
});
}
@Override
public void connect(ITerminalControl term_control) {
try {
term_control.setState(TerminalState.CONNECTING);
term_control.setEncoding("UTF8");
rtt = term_control.getRemoteToTerminalOutputStream();
Protocol.invokeAndWait(new Runnable() {
@Override
public void run() {
pages.add(ViewPage.this);
for (Message m : history) inp_queue.add(m);
inp_thread.setName("TCF Console Input");
inp_thread.start();
}
});
term_control.setState(TerminalState.CONNECTED);
}
catch (Exception x) {
Activator.log("Cannot connect a terminal", x);
term_control.setState(TerminalState.CLOSED);
}
}
@Override
public void setState(TerminalState state) {
}
@Override
public void setTerminalTitle(String title) {
}
}
TCFConsole(final TCFModel model, int type, String ctx_id) {
super(getViewName(type, ctx_id), null, getImageDescriptor(ctx_id), false);
this.model = model;
this.type = type;
this.ctx_id = ctx_id;
display = model.getDisplay();
model.asyncExec(new Runnable() {
public void run() {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
if (!PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isStarting()) {
display.timerExec(200, this);
return;
}
IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager();
manager.addConsoles(new IConsole[]{ TCFConsole.this });
manager.showConsoleView(TCFConsole.this);
}
catch (Throwable x) {
Activator.log("Cannot open Console view", x);
}
}
});
}
private static ImageDescriptor getImageDescriptor(String ctx_id) {
String image = ctx_id != null ? ImageCache.IMG_PROCESS_RUNNING : ImageCache.IMG_TCF;
return ImageCache.getImageDescriptor(image);
}
private static String getViewName(int type, String name) {
String title = "TCF";
switch (type) {
case TYPE_PROCESS_CONSOLE:
title += " Debug Process Console - " + name;
break;
case TYPE_PROCESS_TERMINAL:
title += " Debug Process Terminal - " + name;
break;
case TYPE_UART_TERMINAL:
title += " Debug Virtual Terminal - " + name;
break;
case TYPE_CMD_LINE:
title += " Debugger Command Line";
break;
case TYPE_DPRINTF:
title += " Debugger Dynamic Print";
break;
}
return title;
}
void onModelConnected() {
if (ctx_id != null) {
// Change view title to include context name instead of context ID
Protocol.invokeLater(new Runnable() {
@Override
public void run() {
if (!model.createNode(ctx_id, this)) return;
TCFNode node = (TCFNode)model.getNode(ctx_id);
if (node instanceof TCFNodeExecContext) {
TCFNodeExecContext exe = (TCFNodeExecContext)node;
TCFDataCache<IRunControl.RunControlContext> ctx_cache = exe.getRunContext();
if (!ctx_cache.validate(this)) return;
IRunControl.RunControlContext ctx_data = ctx_cache.getData();
if (ctx_data != null && ctx_data.getName() != null) {
final String name = ctx_data.getName();
model.asyncExec(new Runnable() {
@Override
public void run() {
setName(getViewName(type, name));
}
});
}
}
}
});
}
}
void write(final int stream_id, byte[] data) {
assert Protocol.isDispatchThread();
if (data == null || data.length == 0) return;
Message m = new Message();
m.stream_id = stream_id;
m.data = data;
history.add(m);
if (history.size() > 1000) history.removeFirst();
for (ViewPage p : pages) {
synchronized (p.inp_queue) {
p.inp_queue.add(m);
p.inp_queue.notify();
}
}
}
void close() {
assert Protocol.isDispatchThread();
Message m = new Message();
for (ViewPage p : pages) {
synchronized (p.inp_queue) {
p.inp_queue.add(m);
p.inp_queue.notify();
}
}
model.asyncExec(new Runnable() {
public void run() {
IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager();
manager.removeConsoles(new IConsole[]{ TCFConsole.this });
}
});
}
@Override
public IPageBookViewPage createPage(IConsoleView view) {
return new ViewPage();
}
}
| true | true | public void run() {
try {
for (;;) {
Message m = null;
synchronized (inp_queue) {
while (inp_queue.size() == 0) inp_queue.wait();
m = inp_queue.removeFirst();
}
if (m.data == null) break;
if (type == TYPE_PROCESS_CONSOLE) {
String s = "\u001b[30m";
switch (m.stream_id) {
case 1: s = "\u001b[31m"; break;
case 2: s = "\u001b[34m"; break;
case 3: s = "\u001b[32m"; break;
}
rtt.write(s.getBytes("UTF8"));
for (int i = 0; i < m.data.length; i++) {
int ch = m.data[i] & 0xff;
if (ch == '\n') rtt.write('\r');
rtt.write(ch);
}
}
else {
rtt.write(m.data);
}
}
}
catch (Throwable x) {
Activator.log("Cannot write console output", x);
}
}
| public void run() {
try {
for (;;) {
Message m = null;
synchronized (inp_queue) {
while (inp_queue.size() == 0) inp_queue.wait();
m = inp_queue.removeFirst();
}
if (m.data == null) break;
if (type == TYPE_PROCESS_CONSOLE) {
String s = "\u001b[30m";
switch (m.stream_id) {
case 1: s = "\u001b[31m"; break;
case 2: s = "\u001b[34m"; break;
case 3: s = "\u001b[32m"; break;
}
rtt.write(s.getBytes("UTF8"));
for (int i = 0; i < m.data.length; i++) {
int ch = m.data[i] & 0xff;
if (ch == '\n') rtt.write('\r');
rtt.write(ch);
}
}
else if (type == TYPE_DPRINTF) {
int i = 0;
for (int j = 0; j < m.data.length; j++) {
if (m.data[j] == '\n') {
rtt.write(m.data, i, j - i);
rtt.write('\r');
i = j;
}
}
rtt.write(m.data, i, m.data.length - i);
}
else {
rtt.write(m.data);
}
}
}
catch (Throwable x) {
Activator.log("Cannot write console output", x);
}
}
|
diff --git a/src/com/example/myauto/ListAdapter.java b/src/com/example/myauto/ListAdapter.java
index 407c367..b3fe919 100644
--- a/src/com/example/myauto/ListAdapter.java
+++ b/src/com/example/myauto/ListAdapter.java
@@ -1,73 +1,74 @@
package com.example.myauto;
import java.io.Serializable;
import java.util.ArrayList;//
import com.example.myauto.item.CarFacade;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter{
private ArrayList<CarFacade> ls;
private Context c;
public ListAdapter(ArrayList<CarFacade> list, Context context){
ls = list;
c = context;
}
@Override
public int getCount() {
return ls.size();
}
@Override
public Object getItem(int arg0) {
return ls.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
View v = null;
Container cont;
if (arg1 == null) {
v = View.inflate(c, R.layout.component, null);
cont = new Container();
cont.img = (ImageView) v.findViewById(R.id.image);
cont.name = (TextView) v.findViewById(R.id.product_name);
cont.year = (TextView) v.findViewById(R.id.product_description);
cont.price = (TextView) v.findViewById(R.id.product_price);
v.setTag(cont);
} else {
v = arg1;
cont = (Container) v.getTag();
}
CarFacade cr = ls.get(arg0);
if(cr.hasImage())
(cont.img).setImageBitmap(cr.getImage());
+ else (cont.img).setImageResource(R.drawable.ic_launcher);
(cont.name).setText(cr.getValueFromProperty("name"));
(cont.year).setText(cr.getValueFromProperty("year"));
(cont.price).setText(cr.getValueFromProperty("price"));
return v;
}
private class Container implements Serializable{
private static final long serialVersionUID = 1L;
ImageView img;
TextView name;
TextView year;
TextView price;
}
}
| true | true | public View getView(int arg0, View arg1, ViewGroup arg2) {
View v = null;
Container cont;
if (arg1 == null) {
v = View.inflate(c, R.layout.component, null);
cont = new Container();
cont.img = (ImageView) v.findViewById(R.id.image);
cont.name = (TextView) v.findViewById(R.id.product_name);
cont.year = (TextView) v.findViewById(R.id.product_description);
cont.price = (TextView) v.findViewById(R.id.product_price);
v.setTag(cont);
} else {
v = arg1;
cont = (Container) v.getTag();
}
CarFacade cr = ls.get(arg0);
if(cr.hasImage())
(cont.img).setImageBitmap(cr.getImage());
(cont.name).setText(cr.getValueFromProperty("name"));
(cont.year).setText(cr.getValueFromProperty("year"));
(cont.price).setText(cr.getValueFromProperty("price"));
return v;
}
| public View getView(int arg0, View arg1, ViewGroup arg2) {
View v = null;
Container cont;
if (arg1 == null) {
v = View.inflate(c, R.layout.component, null);
cont = new Container();
cont.img = (ImageView) v.findViewById(R.id.image);
cont.name = (TextView) v.findViewById(R.id.product_name);
cont.year = (TextView) v.findViewById(R.id.product_description);
cont.price = (TextView) v.findViewById(R.id.product_price);
v.setTag(cont);
} else {
v = arg1;
cont = (Container) v.getTag();
}
CarFacade cr = ls.get(arg0);
if(cr.hasImage())
(cont.img).setImageBitmap(cr.getImage());
else (cont.img).setImageResource(R.drawable.ic_launcher);
(cont.name).setText(cr.getValueFromProperty("name"));
(cont.year).setText(cr.getValueFromProperty("year"));
(cont.price).setText(cr.getValueFromProperty("price"));
return v;
}
|
diff --git a/loci/formats/in/MetamorphReader.java b/loci/formats/in/MetamorphReader.java
index 2ce1c6538..556e0b51e 100644
--- a/loci/formats/in/MetamorphReader.java
+++ b/loci/formats/in/MetamorphReader.java
@@ -1,586 +1,586 @@
//
// MetamorphReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.IOException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import loci.formats.DataTools;
import loci.formats.FormatException;
import loci.formats.TiffIFDEntry;
import loci.formats.TiffRational;
import loci.formats.TiffTools;
/**
* Reader is the file format reader for Metamorph STK files.
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert linkert at cs.wisc.edu
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class MetamorphReader extends BaseTiffReader {
// -- Constants --
// IFD tag numbers of important fields
private static final int METAMORPH_ID = 33629;
private static final int UIC2TAG = 33629;
private static final int UIC3TAG = 33630;
private static final int UIC4TAG = 33631;
// -- Fields --
/** The TIFF's name */
private String imageName;
/** The TIFF's creation date */
private String imageCreationDate;
//** The TIFF's emWavelength */
private long[] emWavelength;
// -- Constructor --
/** Constructs a new Metamorph reader. */
public MetamorphReader() { super("Metamorph STK", "stk"); }
// -- FormatReader API methods --
/** Checks if the given block is a valid header for a Metamorph file. */
public boolean isThisType(byte[] block) {
// If the file is a Metamorph STK file, it should have a specific IFD tag.
// Most Metamorph files seem to have the IFD information at the end, so it
// is difficult to determine whether or not the block is a Metamorph block
// without being passed the entire file. Therefore, we will check the only
// things we can reasonably check at the beginning of the file, and if we
// happen to be passed the entire file, well, great, we'll check that too.
// Must be little-endian TIFF
if (block.length < 3) return false;
if (block[0] != TiffTools.LITTLE) return false; // denotes little-endian
if (block[1] != TiffTools.LITTLE) return false;
if (block[2] != TiffTools.MAGIC_NUMBER) return false; // denotes TIFF
if (block.length < 8) return true; // we have no way of verifying further
int ifdlocation = DataTools.bytesToInt(block, 4, true);
if (ifdlocation + 1 > block.length) {
// we have no way of verifying this is a Metamorph file.
// It is at least a TIFF.
return true;
}
else {
int ifdnumber = DataTools.bytesToInt(block, ifdlocation, 2, true);
for (int i = 0; i < ifdnumber; i++) {
if (ifdlocation + 3 + (i * 12) > block.length) return true;
else {
int ifdtag = DataTools.bytesToInt(block,
ifdlocation + 2 + (i * 12), 2, true);
if (ifdtag == METAMORPH_ID) return true; // absolutely a valid file
}
}
return false; // we went through the IFD; the ID wasn't found.
}
}
/**
* Allows the client to specify whether or not to separate channels.
* By default, channels are left unseparated; thus if we encounter an RGB
* image plane, it will be left as RGB and not split into 3 separate planes.
*/
public void setSeparated(boolean separate) {
separated = separate;
super.setSeparated(separate);
}
/** Get the size of the Z dimension. */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return TiffTools.getIFDLongArray(ifds[0], UIC2TAG, true).length;
}
/** Get the size of the T dimension. */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
if (separated) return getImageCount(id) / (getSizeZ(id) * getSizeC(id));
return getImageCount(id) / getSizeZ(id);
}
// -- Internal BaseTiffReader API methods --
/** Populates the metadata hashtable. */
protected void initStandardMetadata() {
super.initStandardMetadata();
try {
// Now that the base TIFF standard metadata has been parsed, we need to
// parse out the STK metadata from the UIC4TAG.
TiffIFDEntry uic4tagEntry = TiffTools.getFirstIFDEntry(in, UIC4TAG);
in.seek(uic4tagEntry.getValueOffset());
int planes = uic4tagEntry.getValueCount();
// Loop through and parse out each field of the UIC4TAG. A field whose
// code is "0" represents the end of the UIC4TAG's fields so we'll stop
// when we reach that; much like a NULL terminated C string.
int currentcode = in.readShort();
byte[] toread;
while (currentcode != 0) {
// variable declarations, because switch is dumb
int num, denom;
int xnum, xdenom, ynum, ydenom;
double xpos, ypos;
String thedate, thetime;
switch (currentcode) {
case 1:
put("MinScale", in.readInt());
break;
case 2:
put("MaxScale", in.readInt());
break;
case 3:
int calib = in.readInt();
String calibration = calib == 0 ? "on" : "off";
put("Spatial Calibration", calibration);
break;
case 4:
num = in.readInt();
denom = in.readInt();
put("XCalibration", new TiffRational(num, denom));
break;
case 5:
num = in.readInt();
denom = in.readInt();
put("YCalibration", new TiffRational(num, denom));
break;
case 6:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("CalibrationUnits", new String(toread));
break;
case 7:
num = in.readInt();
toread = new byte[num];
in.read(toread);
String name = new String(toread);
put("Name", name);
imageName = name;
break;
case 8:
int thresh = in.readInt();
String threshState = "off";
if (thresh == 1) threshState = "inside";
else if (thresh == 2) threshState = "outside";
put("ThreshState", threshState);
break;
case 9:
put("ThreshStateRed", in.readInt());
break;
// there is no 10
case 11:
put("ThreshStateGreen", in.readInt());
break;
case 12:
put("ThreshStateBlue", in.readInt());
break;
case 13:
put("ThreshStateLo", in.readInt());
break;
case 14:
put("ThreshStateHi", in.readInt());
break;
case 15:
int zoom = in.readInt();
put("Zoom", zoom);
// OMETools.setAttribute(ome, "DisplayOptions", "Zoom", "" + zoom);
break;
case 16: // oh how we hate you Julian format...
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("DateTime", thedate + " " + thetime);
imageCreationDate = thedate + " " + thetime;
break;
case 17:
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("LastSavedTime", thedate + " " + thetime);
break;
case 18:
put("currentBuffer", in.readInt());
break;
case 19:
put("grayFit", in.readInt());
break;
case 20:
put("grayPointCount", in.readInt());
break;
case 21:
num = in.readInt();
denom = in.readInt();
put("grayX", new TiffRational(num, denom));
break;
case 22:
num = in.readInt();
denom = in.readInt();
put("gray", new TiffRational(num, denom));
break;
case 23:
num = in.readInt();
denom = in.readInt();
put("grayMin", new TiffRational(num, denom));
break;
case 24:
num = in.readInt();
denom = in.readInt();
put("grayMax", new TiffRational(num, denom));
break;
case 25:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("grayUnitName", new String(toread));
break;
case 26:
int standardLUT = in.readInt();
String standLUT;
switch (standardLUT) {
case 0: standLUT = "monochrome"; break;
case 1: standLUT = "pseudocolor"; break;
case 2: standLUT = "Red"; break;
case 3: standLUT = "Green"; break;
case 4: standLUT = "Blue"; break;
case 5: standLUT = "user-defined"; break;
default: standLUT = "monochrome"; break;
}
put("StandardLUT", standLUT);
break;
case 27:
put("Wavelength", in.readInt());
break;
case 28:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Stage Position Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 29:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Camera Offset Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 30:
put("OverlayMask", in.readInt());
break;
case 31:
put("OverlayCompress", in.readInt());
break;
case 32:
put("Overlay", in.readInt());
break;
case 33:
put("SpecialOverlayMask", in.readInt());
break;
case 34:
put("SpecialOverlayCompress", in.readInt());
break;
case 35:
put("SpecialOverlay", in.readInt());
break;
case 36:
put("ImageProperty", in.readInt());
break;
case 37:
for (int i = 0; i<planes; i++) {
num = in.readInt();
toread = new byte[num];
in.read(toread);
String s = new String(toread);
put("StageLabel Plane " + i, s);
}
break;
case 38:
num = in.readInt();
denom = in.readInt();
put("AutoScaleLoInfo", new TiffRational(num, denom));
break;
case 39:
num = in.readInt();
denom = in.readInt();
put("AutoScaleHiInfo", new TiffRational(num, denom));
break;
case 40:
for (int i=0;i<planes;i++) {
num = in.readInt();
denom = in.readInt();
put("AbsoluteZ Plane " + i, new TiffRational(num, denom));
}
break;
case 41:
for (int i=0; i<planes; i++) {
put("AbsoluteZValid Plane " + i, in.readInt());
}
break;
case 42:
put("Gamma", in.readInt());
break;
case 43:
put("GammaRed", in.readInt());
break;
case 44:
put("GammaGreen", in.readInt());
break;
case 45:
put("GammaBlue", in.readInt());
break;
} // end switch
currentcode = in.readShort();
}
// copy ifds into a new array of Hashtables that will accomodate the
// additional image planes
long[] uic2 = TiffTools.getIFDLongArray(ifds[0], UIC2TAG, true);
numImages = uic2.length;
Hashtable[] tempIFDs = new Hashtable[ifds.length + numImages];
System.arraycopy(ifds, 0, tempIFDs, 0, ifds.length);
int pointer = ifds.length;
long[] oldOffsets = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_OFFSETS, true);
long[] stripByteCounts = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_BYTE_COUNTS, true);
int stripsPerImage = oldOffsets.length;
emWavelength = TiffTools.getIFDLongArray(ifds[0], UIC3TAG, true);
// for each image plane, construct an IFD hashtable
Hashtable temp;
- for(int i=1; i<numImages; i++) {
+ for(int i=0; i<numImages; i++) {
temp = new Hashtable();
// copy most of the data from 1st IFD
temp.put(new Integer(TiffTools.LITTLE_ENDIAN), ifds[0].get(
new Integer(TiffTools.LITTLE_ENDIAN)));
temp.put(new Integer(TiffTools.IMAGE_WIDTH), ifds[0].get(
new Integer(TiffTools.IMAGE_WIDTH)));
temp.put(new Integer(TiffTools.IMAGE_LENGTH),
ifds[0].get(new Integer(TiffTools.IMAGE_LENGTH)));
temp.put(new Integer(TiffTools.BITS_PER_SAMPLE), ifds[0].get(
new Integer(TiffTools.BITS_PER_SAMPLE)));
temp.put(new Integer(TiffTools.COMPRESSION), ifds[0].get(
new Integer(TiffTools.COMPRESSION)));
temp.put(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION),
ifds[0].get(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION)));
temp.put(new Integer(TiffTools.STRIP_BYTE_COUNTS), ifds[0].get(
new Integer(TiffTools.STRIP_BYTE_COUNTS)));
temp.put(new Integer(TiffTools.ROWS_PER_STRIP), ifds[0].get(
new Integer(TiffTools.ROWS_PER_STRIP)));
temp.put(new Integer(TiffTools.X_RESOLUTION), ifds[0].get(
new Integer(TiffTools.X_RESOLUTION)));
temp.put(new Integer(TiffTools.Y_RESOLUTION), ifds[0].get(
new Integer(TiffTools.Y_RESOLUTION)));
temp.put(new Integer(TiffTools.RESOLUTION_UNIT), ifds[0].get(
new Integer(TiffTools.RESOLUTION_UNIT)));
temp.put(new Integer(TiffTools.PREDICTOR), ifds[0].get(
new Integer(TiffTools.PREDICTOR)));
// now we need a StripOffsets entry
long planeOffset = i*(oldOffsets[stripsPerImage - 1] +
stripByteCounts[stripsPerImage - 1] - oldOffsets[0]);
long[] newOffsets = new long[oldOffsets.length];
newOffsets[0] = planeOffset + oldOffsets[0];
for(int j=1; j<newOffsets.length; j++) {
newOffsets[j] = newOffsets[j-1] + stripByteCounts[0];
}
temp.put(new Integer(TiffTools.STRIP_OFFSETS), newOffsets);
tempIFDs[pointer] = temp;
pointer++;
}
ifds = tempIFDs;
}
catch (NullPointerException n) { n.printStackTrace(); }
catch (IOException io) { io.printStackTrace(); }
catch (FormatException e) { e.printStackTrace(); }
try { super.initStandardMetadata(); }
catch (Throwable t) { t.printStackTrace(); }
// parse (mangle) TIFF comment
String descr = (String) metadata.get("Comment");
if (descr != null) {
StringTokenizer st = new StringTokenizer(descr, "\n");
StringBuffer sb = new StringBuffer();
boolean first = true;
while (st.hasMoreTokens()) {
String line = st.nextToken();
int colon = line.indexOf(": ");
if (colon < 0) {
// normal line (not a key/value pair)
if (line.trim().length() > 0) {
// not a blank line
sb.append(line);
if (!line.endsWith(".")) sb.append(".");
sb.append(" ");
}
first = false;
continue;
}
if (first) {
// first line could be mangled; make a reasonable guess
int dot = line.lastIndexOf(".", colon);
if (dot >= 0) {
String s = line.substring(0, dot + 1);
sb.append(s);
if (!s.endsWith(".")) sb.append(".");
sb.append(" ");
}
line = line.substring(dot + 1);
colon -= dot + 1;
first = false;
}
// add key/value pair embedded in comment as separate metadata
String key = line.substring(0, colon);
String value = line.substring(colon + 2);
put(key, value);
}
// replace comment with trimmed version
descr = sb.toString().trim();
if (descr.equals("")) metadata.remove("Comment");
else put("Comment", descr);
}
}
/*
* (non-Javadoc)
* @see loci.formats.BaseTiffReader#getImageName()
*/
protected String getImageName() {
if (imageName == null) return super.getImageName();
return imageName;
}
/*
* (non-Javadoc)
* @see loci.formats.BaseTiffReader#getImageCreationDate()
*/
protected String getImageCreationDate() {
if (imageCreationDate == null) return super.getImageCreationDate();
return imageCreationDate;
}
protected void setChannelGlobalMinMax(int i)
throws FormatException, IOException
{
Double globalMin = (Double) metadata.get("grayMin");
Double globalMax = (Double) metadata.get("grayMax");
if (globalMin != null | globalMax != null)
{
getMetadataStore(currentId).setChannelGlobalMinMax(i,
globalMin,globalMax, null);
}
super.setChannelGlobalMinMax(i);
}
Integer getEmWave(int i) {
if (emWavelength[i] == 0) return null;
return new Integer((int) emWavelength[i]);
}
// -- Utility methods --
/** Converts a Julian date value into a human-readable string. */
public static String decodeDate(int julian) {
long a, b, c, d, e, alpha, z;
short day, month, year;
// code reused from the Metamorph data specification
z = julian + 1;
if (z < 2299161L) a = z;
else {
alpha = (long) ((z - 1867216.25) / 36524.25);
a = z + 1 + alpha - alpha / 4;
}
b = (a > 1721423L ? a + 1524 : a + 1158);
c = (long) ((b - 122.1) / 365.25);
d = (long) (365.25 * c);
e = (long) ((b - d) / 30.6001);
day = (short) (b - d - (long) (30.6001 * e));
month = (short) ((e < 13.5) ? e - 1 : e - 13);
year = (short) ((month > 2.5) ? (c - 4716) : c - 4715);
return day + "/" + month + "/" + year;
}
/** Converts a time value in milliseconds into a human-readable string. */
public static String decodeTime(int millis) {
int ms, seconds, minutes, hours;
ms = millis % 1000;
millis -= ms;
millis /= 1000;
seconds = millis % 60;
millis -= seconds;
millis /= 60;
minutes = millis % 60;
millis -= minutes;
millis /= 60;
hours = millis;
return hours + ":" + minutes + ":" + seconds + "." + ms;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new MetamorphReader().testRead(args);
}
}
| true | true | protected void initStandardMetadata() {
super.initStandardMetadata();
try {
// Now that the base TIFF standard metadata has been parsed, we need to
// parse out the STK metadata from the UIC4TAG.
TiffIFDEntry uic4tagEntry = TiffTools.getFirstIFDEntry(in, UIC4TAG);
in.seek(uic4tagEntry.getValueOffset());
int planes = uic4tagEntry.getValueCount();
// Loop through and parse out each field of the UIC4TAG. A field whose
// code is "0" represents the end of the UIC4TAG's fields so we'll stop
// when we reach that; much like a NULL terminated C string.
int currentcode = in.readShort();
byte[] toread;
while (currentcode != 0) {
// variable declarations, because switch is dumb
int num, denom;
int xnum, xdenom, ynum, ydenom;
double xpos, ypos;
String thedate, thetime;
switch (currentcode) {
case 1:
put("MinScale", in.readInt());
break;
case 2:
put("MaxScale", in.readInt());
break;
case 3:
int calib = in.readInt();
String calibration = calib == 0 ? "on" : "off";
put("Spatial Calibration", calibration);
break;
case 4:
num = in.readInt();
denom = in.readInt();
put("XCalibration", new TiffRational(num, denom));
break;
case 5:
num = in.readInt();
denom = in.readInt();
put("YCalibration", new TiffRational(num, denom));
break;
case 6:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("CalibrationUnits", new String(toread));
break;
case 7:
num = in.readInt();
toread = new byte[num];
in.read(toread);
String name = new String(toread);
put("Name", name);
imageName = name;
break;
case 8:
int thresh = in.readInt();
String threshState = "off";
if (thresh == 1) threshState = "inside";
else if (thresh == 2) threshState = "outside";
put("ThreshState", threshState);
break;
case 9:
put("ThreshStateRed", in.readInt());
break;
// there is no 10
case 11:
put("ThreshStateGreen", in.readInt());
break;
case 12:
put("ThreshStateBlue", in.readInt());
break;
case 13:
put("ThreshStateLo", in.readInt());
break;
case 14:
put("ThreshStateHi", in.readInt());
break;
case 15:
int zoom = in.readInt();
put("Zoom", zoom);
// OMETools.setAttribute(ome, "DisplayOptions", "Zoom", "" + zoom);
break;
case 16: // oh how we hate you Julian format...
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("DateTime", thedate + " " + thetime);
imageCreationDate = thedate + " " + thetime;
break;
case 17:
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("LastSavedTime", thedate + " " + thetime);
break;
case 18:
put("currentBuffer", in.readInt());
break;
case 19:
put("grayFit", in.readInt());
break;
case 20:
put("grayPointCount", in.readInt());
break;
case 21:
num = in.readInt();
denom = in.readInt();
put("grayX", new TiffRational(num, denom));
break;
case 22:
num = in.readInt();
denom = in.readInt();
put("gray", new TiffRational(num, denom));
break;
case 23:
num = in.readInt();
denom = in.readInt();
put("grayMin", new TiffRational(num, denom));
break;
case 24:
num = in.readInt();
denom = in.readInt();
put("grayMax", new TiffRational(num, denom));
break;
case 25:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("grayUnitName", new String(toread));
break;
case 26:
int standardLUT = in.readInt();
String standLUT;
switch (standardLUT) {
case 0: standLUT = "monochrome"; break;
case 1: standLUT = "pseudocolor"; break;
case 2: standLUT = "Red"; break;
case 3: standLUT = "Green"; break;
case 4: standLUT = "Blue"; break;
case 5: standLUT = "user-defined"; break;
default: standLUT = "monochrome"; break;
}
put("StandardLUT", standLUT);
break;
case 27:
put("Wavelength", in.readInt());
break;
case 28:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Stage Position Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 29:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Camera Offset Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 30:
put("OverlayMask", in.readInt());
break;
case 31:
put("OverlayCompress", in.readInt());
break;
case 32:
put("Overlay", in.readInt());
break;
case 33:
put("SpecialOverlayMask", in.readInt());
break;
case 34:
put("SpecialOverlayCompress", in.readInt());
break;
case 35:
put("SpecialOverlay", in.readInt());
break;
case 36:
put("ImageProperty", in.readInt());
break;
case 37:
for (int i = 0; i<planes; i++) {
num = in.readInt();
toread = new byte[num];
in.read(toread);
String s = new String(toread);
put("StageLabel Plane " + i, s);
}
break;
case 38:
num = in.readInt();
denom = in.readInt();
put("AutoScaleLoInfo", new TiffRational(num, denom));
break;
case 39:
num = in.readInt();
denom = in.readInt();
put("AutoScaleHiInfo", new TiffRational(num, denom));
break;
case 40:
for (int i=0;i<planes;i++) {
num = in.readInt();
denom = in.readInt();
put("AbsoluteZ Plane " + i, new TiffRational(num, denom));
}
break;
case 41:
for (int i=0; i<planes; i++) {
put("AbsoluteZValid Plane " + i, in.readInt());
}
break;
case 42:
put("Gamma", in.readInt());
break;
case 43:
put("GammaRed", in.readInt());
break;
case 44:
put("GammaGreen", in.readInt());
break;
case 45:
put("GammaBlue", in.readInt());
break;
} // end switch
currentcode = in.readShort();
}
// copy ifds into a new array of Hashtables that will accomodate the
// additional image planes
long[] uic2 = TiffTools.getIFDLongArray(ifds[0], UIC2TAG, true);
numImages = uic2.length;
Hashtable[] tempIFDs = new Hashtable[ifds.length + numImages];
System.arraycopy(ifds, 0, tempIFDs, 0, ifds.length);
int pointer = ifds.length;
long[] oldOffsets = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_OFFSETS, true);
long[] stripByteCounts = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_BYTE_COUNTS, true);
int stripsPerImage = oldOffsets.length;
emWavelength = TiffTools.getIFDLongArray(ifds[0], UIC3TAG, true);
// for each image plane, construct an IFD hashtable
Hashtable temp;
for(int i=1; i<numImages; i++) {
temp = new Hashtable();
// copy most of the data from 1st IFD
temp.put(new Integer(TiffTools.LITTLE_ENDIAN), ifds[0].get(
new Integer(TiffTools.LITTLE_ENDIAN)));
temp.put(new Integer(TiffTools.IMAGE_WIDTH), ifds[0].get(
new Integer(TiffTools.IMAGE_WIDTH)));
temp.put(new Integer(TiffTools.IMAGE_LENGTH),
ifds[0].get(new Integer(TiffTools.IMAGE_LENGTH)));
temp.put(new Integer(TiffTools.BITS_PER_SAMPLE), ifds[0].get(
new Integer(TiffTools.BITS_PER_SAMPLE)));
temp.put(new Integer(TiffTools.COMPRESSION), ifds[0].get(
new Integer(TiffTools.COMPRESSION)));
temp.put(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION),
ifds[0].get(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION)));
temp.put(new Integer(TiffTools.STRIP_BYTE_COUNTS), ifds[0].get(
new Integer(TiffTools.STRIP_BYTE_COUNTS)));
temp.put(new Integer(TiffTools.ROWS_PER_STRIP), ifds[0].get(
new Integer(TiffTools.ROWS_PER_STRIP)));
temp.put(new Integer(TiffTools.X_RESOLUTION), ifds[0].get(
new Integer(TiffTools.X_RESOLUTION)));
temp.put(new Integer(TiffTools.Y_RESOLUTION), ifds[0].get(
new Integer(TiffTools.Y_RESOLUTION)));
temp.put(new Integer(TiffTools.RESOLUTION_UNIT), ifds[0].get(
new Integer(TiffTools.RESOLUTION_UNIT)));
temp.put(new Integer(TiffTools.PREDICTOR), ifds[0].get(
new Integer(TiffTools.PREDICTOR)));
// now we need a StripOffsets entry
long planeOffset = i*(oldOffsets[stripsPerImage - 1] +
stripByteCounts[stripsPerImage - 1] - oldOffsets[0]);
long[] newOffsets = new long[oldOffsets.length];
newOffsets[0] = planeOffset + oldOffsets[0];
for(int j=1; j<newOffsets.length; j++) {
newOffsets[j] = newOffsets[j-1] + stripByteCounts[0];
}
temp.put(new Integer(TiffTools.STRIP_OFFSETS), newOffsets);
tempIFDs[pointer] = temp;
pointer++;
}
ifds = tempIFDs;
}
catch (NullPointerException n) { n.printStackTrace(); }
catch (IOException io) { io.printStackTrace(); }
catch (FormatException e) { e.printStackTrace(); }
try { super.initStandardMetadata(); }
catch (Throwable t) { t.printStackTrace(); }
// parse (mangle) TIFF comment
String descr = (String) metadata.get("Comment");
if (descr != null) {
StringTokenizer st = new StringTokenizer(descr, "\n");
StringBuffer sb = new StringBuffer();
boolean first = true;
while (st.hasMoreTokens()) {
String line = st.nextToken();
int colon = line.indexOf(": ");
if (colon < 0) {
// normal line (not a key/value pair)
if (line.trim().length() > 0) {
// not a blank line
sb.append(line);
if (!line.endsWith(".")) sb.append(".");
sb.append(" ");
}
first = false;
continue;
}
if (first) {
// first line could be mangled; make a reasonable guess
int dot = line.lastIndexOf(".", colon);
if (dot >= 0) {
String s = line.substring(0, dot + 1);
sb.append(s);
if (!s.endsWith(".")) sb.append(".");
sb.append(" ");
}
line = line.substring(dot + 1);
colon -= dot + 1;
first = false;
}
// add key/value pair embedded in comment as separate metadata
String key = line.substring(0, colon);
String value = line.substring(colon + 2);
put(key, value);
}
// replace comment with trimmed version
descr = sb.toString().trim();
if (descr.equals("")) metadata.remove("Comment");
else put("Comment", descr);
}
}
| protected void initStandardMetadata() {
super.initStandardMetadata();
try {
// Now that the base TIFF standard metadata has been parsed, we need to
// parse out the STK metadata from the UIC4TAG.
TiffIFDEntry uic4tagEntry = TiffTools.getFirstIFDEntry(in, UIC4TAG);
in.seek(uic4tagEntry.getValueOffset());
int planes = uic4tagEntry.getValueCount();
// Loop through and parse out each field of the UIC4TAG. A field whose
// code is "0" represents the end of the UIC4TAG's fields so we'll stop
// when we reach that; much like a NULL terminated C string.
int currentcode = in.readShort();
byte[] toread;
while (currentcode != 0) {
// variable declarations, because switch is dumb
int num, denom;
int xnum, xdenom, ynum, ydenom;
double xpos, ypos;
String thedate, thetime;
switch (currentcode) {
case 1:
put("MinScale", in.readInt());
break;
case 2:
put("MaxScale", in.readInt());
break;
case 3:
int calib = in.readInt();
String calibration = calib == 0 ? "on" : "off";
put("Spatial Calibration", calibration);
break;
case 4:
num = in.readInt();
denom = in.readInt();
put("XCalibration", new TiffRational(num, denom));
break;
case 5:
num = in.readInt();
denom = in.readInt();
put("YCalibration", new TiffRational(num, denom));
break;
case 6:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("CalibrationUnits", new String(toread));
break;
case 7:
num = in.readInt();
toread = new byte[num];
in.read(toread);
String name = new String(toread);
put("Name", name);
imageName = name;
break;
case 8:
int thresh = in.readInt();
String threshState = "off";
if (thresh == 1) threshState = "inside";
else if (thresh == 2) threshState = "outside";
put("ThreshState", threshState);
break;
case 9:
put("ThreshStateRed", in.readInt());
break;
// there is no 10
case 11:
put("ThreshStateGreen", in.readInt());
break;
case 12:
put("ThreshStateBlue", in.readInt());
break;
case 13:
put("ThreshStateLo", in.readInt());
break;
case 14:
put("ThreshStateHi", in.readInt());
break;
case 15:
int zoom = in.readInt();
put("Zoom", zoom);
// OMETools.setAttribute(ome, "DisplayOptions", "Zoom", "" + zoom);
break;
case 16: // oh how we hate you Julian format...
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("DateTime", thedate + " " + thetime);
imageCreationDate = thedate + " " + thetime;
break;
case 17:
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
put("LastSavedTime", thedate + " " + thetime);
break;
case 18:
put("currentBuffer", in.readInt());
break;
case 19:
put("grayFit", in.readInt());
break;
case 20:
put("grayPointCount", in.readInt());
break;
case 21:
num = in.readInt();
denom = in.readInt();
put("grayX", new TiffRational(num, denom));
break;
case 22:
num = in.readInt();
denom = in.readInt();
put("gray", new TiffRational(num, denom));
break;
case 23:
num = in.readInt();
denom = in.readInt();
put("grayMin", new TiffRational(num, denom));
break;
case 24:
num = in.readInt();
denom = in.readInt();
put("grayMax", new TiffRational(num, denom));
break;
case 25:
num = in.readInt();
toread = new byte[num];
in.read(toread);
put("grayUnitName", new String(toread));
break;
case 26:
int standardLUT = in.readInt();
String standLUT;
switch (standardLUT) {
case 0: standLUT = "monochrome"; break;
case 1: standLUT = "pseudocolor"; break;
case 2: standLUT = "Red"; break;
case 3: standLUT = "Green"; break;
case 4: standLUT = "Blue"; break;
case 5: standLUT = "user-defined"; break;
default: standLUT = "monochrome"; break;
}
put("StandardLUT", standLUT);
break;
case 27:
put("Wavelength", in.readInt());
break;
case 28:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Stage Position Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 29:
for (int i = 0; i < planes; i++) {
xnum = in.readInt();
xdenom = in.readInt();
ynum = in.readInt();
ydenom = in.readInt();
xpos = xnum / xdenom;
ypos = ynum / ydenom;
put("Camera Offset Plane " + i,
"(" + xpos + ", " + ypos + ")");
}
break;
case 30:
put("OverlayMask", in.readInt());
break;
case 31:
put("OverlayCompress", in.readInt());
break;
case 32:
put("Overlay", in.readInt());
break;
case 33:
put("SpecialOverlayMask", in.readInt());
break;
case 34:
put("SpecialOverlayCompress", in.readInt());
break;
case 35:
put("SpecialOverlay", in.readInt());
break;
case 36:
put("ImageProperty", in.readInt());
break;
case 37:
for (int i = 0; i<planes; i++) {
num = in.readInt();
toread = new byte[num];
in.read(toread);
String s = new String(toread);
put("StageLabel Plane " + i, s);
}
break;
case 38:
num = in.readInt();
denom = in.readInt();
put("AutoScaleLoInfo", new TiffRational(num, denom));
break;
case 39:
num = in.readInt();
denom = in.readInt();
put("AutoScaleHiInfo", new TiffRational(num, denom));
break;
case 40:
for (int i=0;i<planes;i++) {
num = in.readInt();
denom = in.readInt();
put("AbsoluteZ Plane " + i, new TiffRational(num, denom));
}
break;
case 41:
for (int i=0; i<planes; i++) {
put("AbsoluteZValid Plane " + i, in.readInt());
}
break;
case 42:
put("Gamma", in.readInt());
break;
case 43:
put("GammaRed", in.readInt());
break;
case 44:
put("GammaGreen", in.readInt());
break;
case 45:
put("GammaBlue", in.readInt());
break;
} // end switch
currentcode = in.readShort();
}
// copy ifds into a new array of Hashtables that will accomodate the
// additional image planes
long[] uic2 = TiffTools.getIFDLongArray(ifds[0], UIC2TAG, true);
numImages = uic2.length;
Hashtable[] tempIFDs = new Hashtable[ifds.length + numImages];
System.arraycopy(ifds, 0, tempIFDs, 0, ifds.length);
int pointer = ifds.length;
long[] oldOffsets = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_OFFSETS, true);
long[] stripByteCounts = TiffTools.getIFDLongArray(ifds[0],
TiffTools.STRIP_BYTE_COUNTS, true);
int stripsPerImage = oldOffsets.length;
emWavelength = TiffTools.getIFDLongArray(ifds[0], UIC3TAG, true);
// for each image plane, construct an IFD hashtable
Hashtable temp;
for(int i=0; i<numImages; i++) {
temp = new Hashtable();
// copy most of the data from 1st IFD
temp.put(new Integer(TiffTools.LITTLE_ENDIAN), ifds[0].get(
new Integer(TiffTools.LITTLE_ENDIAN)));
temp.put(new Integer(TiffTools.IMAGE_WIDTH), ifds[0].get(
new Integer(TiffTools.IMAGE_WIDTH)));
temp.put(new Integer(TiffTools.IMAGE_LENGTH),
ifds[0].get(new Integer(TiffTools.IMAGE_LENGTH)));
temp.put(new Integer(TiffTools.BITS_PER_SAMPLE), ifds[0].get(
new Integer(TiffTools.BITS_PER_SAMPLE)));
temp.put(new Integer(TiffTools.COMPRESSION), ifds[0].get(
new Integer(TiffTools.COMPRESSION)));
temp.put(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION),
ifds[0].get(new Integer(TiffTools.PHOTOMETRIC_INTERPRETATION)));
temp.put(new Integer(TiffTools.STRIP_BYTE_COUNTS), ifds[0].get(
new Integer(TiffTools.STRIP_BYTE_COUNTS)));
temp.put(new Integer(TiffTools.ROWS_PER_STRIP), ifds[0].get(
new Integer(TiffTools.ROWS_PER_STRIP)));
temp.put(new Integer(TiffTools.X_RESOLUTION), ifds[0].get(
new Integer(TiffTools.X_RESOLUTION)));
temp.put(new Integer(TiffTools.Y_RESOLUTION), ifds[0].get(
new Integer(TiffTools.Y_RESOLUTION)));
temp.put(new Integer(TiffTools.RESOLUTION_UNIT), ifds[0].get(
new Integer(TiffTools.RESOLUTION_UNIT)));
temp.put(new Integer(TiffTools.PREDICTOR), ifds[0].get(
new Integer(TiffTools.PREDICTOR)));
// now we need a StripOffsets entry
long planeOffset = i*(oldOffsets[stripsPerImage - 1] +
stripByteCounts[stripsPerImage - 1] - oldOffsets[0]);
long[] newOffsets = new long[oldOffsets.length];
newOffsets[0] = planeOffset + oldOffsets[0];
for(int j=1; j<newOffsets.length; j++) {
newOffsets[j] = newOffsets[j-1] + stripByteCounts[0];
}
temp.put(new Integer(TiffTools.STRIP_OFFSETS), newOffsets);
tempIFDs[pointer] = temp;
pointer++;
}
ifds = tempIFDs;
}
catch (NullPointerException n) { n.printStackTrace(); }
catch (IOException io) { io.printStackTrace(); }
catch (FormatException e) { e.printStackTrace(); }
try { super.initStandardMetadata(); }
catch (Throwable t) { t.printStackTrace(); }
// parse (mangle) TIFF comment
String descr = (String) metadata.get("Comment");
if (descr != null) {
StringTokenizer st = new StringTokenizer(descr, "\n");
StringBuffer sb = new StringBuffer();
boolean first = true;
while (st.hasMoreTokens()) {
String line = st.nextToken();
int colon = line.indexOf(": ");
if (colon < 0) {
// normal line (not a key/value pair)
if (line.trim().length() > 0) {
// not a blank line
sb.append(line);
if (!line.endsWith(".")) sb.append(".");
sb.append(" ");
}
first = false;
continue;
}
if (first) {
// first line could be mangled; make a reasonable guess
int dot = line.lastIndexOf(".", colon);
if (dot >= 0) {
String s = line.substring(0, dot + 1);
sb.append(s);
if (!s.endsWith(".")) sb.append(".");
sb.append(" ");
}
line = line.substring(dot + 1);
colon -= dot + 1;
first = false;
}
// add key/value pair embedded in comment as separate metadata
String key = line.substring(0, colon);
String value = line.substring(colon + 2);
put(key, value);
}
// replace comment with trimmed version
descr = sb.toString().trim();
if (descr.equals("")) metadata.remove("Comment");
else put("Comment", descr);
}
}
|
diff --git a/sip-servlets-examples/shopping-demo/business/src/main/java/org/jboss/mobicents/seam/util/DTMFUtils.java b/sip-servlets-examples/shopping-demo/business/src/main/java/org/jboss/mobicents/seam/util/DTMFUtils.java
index 14beeba22..3c6dbcdb1 100644
--- a/sip-servlets-examples/shopping-demo/business/src/main/java/org/jboss/mobicents/seam/util/DTMFUtils.java
+++ b/sip-servlets-examples/shopping-demo/business/src/main/java/org/jboss/mobicents/seam/util/DTMFUtils.java
@@ -1,273 +1,278 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.mobicents.seam.util;
import java.io.File;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.sip.SipSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.mobicents.seam.actions.OrderManager;
import org.jboss.mobicents.seam.listeners.DTMFListener;
import org.jboss.mobicents.seam.listeners.MediaResourceListener;
import org.mobicents.mscontrol.MsConnection;
import org.mobicents.mscontrol.MsSignalGenerator;
import org.mobicents.mscontrol.signal.Announcement;
import org.mobicents.mscontrol.signal.Basic;
/**
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class DTMFUtils {
private static Log logger = LogFactory.getLog(DTMFUtils.class);
public static void adminApproval(SipSession session, String signal, String pathToAudioDirectory) {
if("1".equalsIgnoreCase(signal)) {
// Order Approved
logger.info("Order approved !");
String audioFile = pathToAudioDirectory + "OrderApproved.wav";
playFileInResponseToDTMFInfo(session, audioFile);
// try {
// InitialContext ctx = new InitialContext();
// OrderApproval orderApproval = (OrderApproval) ctx.lookup("shopping-demo/OrderApprovalAction/remote");
// orderApproval.fireOrderApprovedEvent();
// } catch (NamingException e) {
// logger.error("An exception occured while retrieving the EJB OrderApproval",e);
// }
} else if("2".equalsIgnoreCase(signal)) {
// Order Rejected
logger.info("Order rejected !");
String audioFile = pathToAudioDirectory + "OrderCancelled.wav";
playFileInResponseToDTMFInfo(session, audioFile);
// try {
// InitialContext ctx = new InitialContext();
// OrderApproval orderApproval = (OrderApproval) ctx.lookup("shopping-demo/OrderApprovalAction/remote");
// orderApproval.fireOrderRejectedEvent();
// } catch (NamingException e) {
// logger.error("An exception occured while retrieving the EJB OrderApproval",e);
// }
}
}
public static void orderApproval(SipSession session, String signal, String pathToAudioDirectory) {
long orderId = (Long) session.getApplicationSession().getAttribute("orderId");
if("1".equalsIgnoreCase(signal)) {
// Order Confirmed
logger.info("Order " + orderId + " confirmed !");
String audioFile = pathToAudioDirectory + "OrderApproved.wav";
playFileInResponseToDTMFInfo(session, audioFile);
try {
InitialContext ctx = new InitialContext();
OrderManager orderManager = (OrderManager) ctx.lookup("shopping-demo/OrderManagerBean/remote");
orderManager.confirmOrder(orderId);
} catch (NamingException e) {
logger.error("An exception occured while retrieving the EJB OrderManager",e);
}
} else if("2".equalsIgnoreCase(signal)) {
// Order cancelled
logger.info("Order " + orderId + " cancelled !");
String audioFile = pathToAudioDirectory + "OrderCancelled.wav";
playFileInResponseToDTMFInfo(session, audioFile);
try {
InitialContext ctx = new InitialContext();
OrderManager orderManager = (OrderManager) ctx.lookup("shopping-demo/OrderManagerBean/remote");
orderManager.cancelOrder(orderId);
} catch (NamingException e) {
logger.error("An exception occured while retrieving the EJB OrderManager",e);
}
}
}
public static void updateDeliveryDate(SipSession session, String signal) {
- int cause = Integer.parseInt(signal);
+ int cause = -1;
+ try {
+ cause = Integer.parseInt(signal);
+ } catch (java.lang.NumberFormatException e) {
+ return;
+ }
synchronized(session) {
String dateAndTime = (String) session.getAttribute("dateAndTime");
if(dateAndTime == null) {
dateAndTime = "";
}
switch (cause) {
case Basic.CAUSE_DIGIT_0:
dateAndTime = dateAndTime + "0";
break;
case Basic.CAUSE_DIGIT_1:
dateAndTime = dateAndTime + "1";
break;
case Basic.CAUSE_DIGIT_2:
dateAndTime = dateAndTime + "2";
break;
case Basic.CAUSE_DIGIT_3:
dateAndTime = dateAndTime + "3";
break;
case Basic.CAUSE_DIGIT_4:
dateAndTime = dateAndTime + "4";
break;
case Basic.CAUSE_DIGIT_5:
dateAndTime = dateAndTime + "5";
break;
case Basic.CAUSE_DIGIT_6:
dateAndTime = dateAndTime + "6";
break;
case Basic.CAUSE_DIGIT_7:
dateAndTime = dateAndTime + "7";
break;
case Basic.CAUSE_DIGIT_8:
dateAndTime = dateAndTime + "8";
break;
case Basic.CAUSE_DIGIT_9:
dateAndTime = dateAndTime + "9";
break;
default:
break;
}
// TODO: Add logic to check if date and time is valid. We assume that
// user is well educated and will always punch right date and time
if (dateAndTime.length() == 10) {
char[] c = dateAndTime.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("You have selected delivery date to be ");
String date = "" + c[0] + c[1];
int iDate = (new Integer(date)).intValue();
stringBuffer.append(iDate);
String month = "" + c[2] + c[3];
int iMonth = (new Integer(month)).intValue();
String year = "" + c[4] + c[5];
int iYear = (new Integer(year)).intValue();
String hour = "" + c[6] + c[7];
int iHour = (new Integer(hour)).intValue();
String min = "" + c[8] + c[9];
int iMin = (new Integer(min)).intValue();
switch (iMonth) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
default:
break;
}
stringBuffer.append(" of ");
stringBuffer.append(month);
stringBuffer.append(" ");
stringBuffer.append(2000 + iYear);
stringBuffer.append(" at ");
stringBuffer.append(iHour);
stringBuffer.append(" hour and ");
stringBuffer.append(iMin);
stringBuffer.append(" minute. Thank you. Bye.");
java.sql.Timestamp timeStamp = new java.sql.Timestamp(
(iYear + 100), iMonth - 1, iDate, iHour, iMin, 0, 0);
try {
InitialContext ctx = new InitialContext();
OrderManager orderManager = (OrderManager) ctx.lookup("shopping-demo/OrderManagerBean/remote");
orderManager.setDeliveryDate(session.getApplicationSession().getAttribute("orderId"), timeStamp);
} catch (NamingException e) {
logger.error("An exception occured while retrieving the EJB OrderManager",e);
}
logger.info(stringBuffer.toString());
try {
TTSUtils.buildAudio(stringBuffer.toString(), "deliveryDate.wav");
MsConnection connection = (MsConnection) session.getApplicationSession().getAttribute("connection");
String endpoint = connection.getEndpoint();
MsSignalGenerator generator = connection.getSession().getProvider().getSignalGenerator(endpoint);
java.io.File speech = new File("deliveryDate.wav");
logger.info("Playing delivery date summary : " + "file://" + speech.getAbsolutePath());
MediaResourceListener mediaResourceListener = new MediaResourceListener(session, connection);
generator.addResourceListener(mediaResourceListener);
generator.apply(Announcement.PLAY, new String[]{"file://" + speech.getAbsolutePath()});
logger.info("delivery Date summary played. waiting for DTMF ");
} catch (Exception e) {
logger.error("An unexpected exception occured while generating the deliveryDate tts file");
}
} else {
session.setAttribute("dateAndTime", dateAndTime);
}
}
}
/**
* Make the media server play a file given in parameter
* and add a listener so that when the media server is done playing the call is tear down
* @param session the sip session used to tear down the call
* @param audioFile the file to play
*/
public static void playFileInResponseToDTMFInfo(SipSession session,
String audioFile) {
MsConnection connection = (MsConnection)session.getApplicationSession().getAttribute("connection");
String endpoint = connection.getEndpoint();
MsSignalGenerator generator = connection.getSession().getProvider().getSignalGenerator(endpoint);
MediaResourceListener mediaResourceListener = new MediaResourceListener(session, connection);
generator.addResourceListener(mediaResourceListener);
generator.apply(Announcement.PLAY, new String[] { audioFile });
session.setAttribute("DTMFSession", DTMFListener.DTMF_SESSION_STOPPED);
}
}
| true | true | public static void updateDeliveryDate(SipSession session, String signal) {
int cause = Integer.parseInt(signal);
synchronized(session) {
String dateAndTime = (String) session.getAttribute("dateAndTime");
if(dateAndTime == null) {
dateAndTime = "";
}
switch (cause) {
case Basic.CAUSE_DIGIT_0:
dateAndTime = dateAndTime + "0";
break;
case Basic.CAUSE_DIGIT_1:
dateAndTime = dateAndTime + "1";
break;
case Basic.CAUSE_DIGIT_2:
dateAndTime = dateAndTime + "2";
break;
case Basic.CAUSE_DIGIT_3:
dateAndTime = dateAndTime + "3";
break;
case Basic.CAUSE_DIGIT_4:
dateAndTime = dateAndTime + "4";
break;
case Basic.CAUSE_DIGIT_5:
dateAndTime = dateAndTime + "5";
break;
case Basic.CAUSE_DIGIT_6:
dateAndTime = dateAndTime + "6";
break;
case Basic.CAUSE_DIGIT_7:
dateAndTime = dateAndTime + "7";
break;
case Basic.CAUSE_DIGIT_8:
dateAndTime = dateAndTime + "8";
break;
case Basic.CAUSE_DIGIT_9:
dateAndTime = dateAndTime + "9";
break;
default:
break;
}
// TODO: Add logic to check if date and time is valid. We assume that
// user is well educated and will always punch right date and time
if (dateAndTime.length() == 10) {
char[] c = dateAndTime.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("You have selected delivery date to be ");
String date = "" + c[0] + c[1];
int iDate = (new Integer(date)).intValue();
stringBuffer.append(iDate);
String month = "" + c[2] + c[3];
int iMonth = (new Integer(month)).intValue();
String year = "" + c[4] + c[5];
int iYear = (new Integer(year)).intValue();
String hour = "" + c[6] + c[7];
int iHour = (new Integer(hour)).intValue();
String min = "" + c[8] + c[9];
int iMin = (new Integer(min)).intValue();
switch (iMonth) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
default:
break;
}
stringBuffer.append(" of ");
stringBuffer.append(month);
stringBuffer.append(" ");
stringBuffer.append(2000 + iYear);
stringBuffer.append(" at ");
stringBuffer.append(iHour);
stringBuffer.append(" hour and ");
stringBuffer.append(iMin);
stringBuffer.append(" minute. Thank you. Bye.");
java.sql.Timestamp timeStamp = new java.sql.Timestamp(
(iYear + 100), iMonth - 1, iDate, iHour, iMin, 0, 0);
try {
InitialContext ctx = new InitialContext();
OrderManager orderManager = (OrderManager) ctx.lookup("shopping-demo/OrderManagerBean/remote");
orderManager.setDeliveryDate(session.getApplicationSession().getAttribute("orderId"), timeStamp);
} catch (NamingException e) {
logger.error("An exception occured while retrieving the EJB OrderManager",e);
}
logger.info(stringBuffer.toString());
try {
TTSUtils.buildAudio(stringBuffer.toString(), "deliveryDate.wav");
MsConnection connection = (MsConnection) session.getApplicationSession().getAttribute("connection");
String endpoint = connection.getEndpoint();
MsSignalGenerator generator = connection.getSession().getProvider().getSignalGenerator(endpoint);
java.io.File speech = new File("deliveryDate.wav");
logger.info("Playing delivery date summary : " + "file://" + speech.getAbsolutePath());
MediaResourceListener mediaResourceListener = new MediaResourceListener(session, connection);
generator.addResourceListener(mediaResourceListener);
generator.apply(Announcement.PLAY, new String[]{"file://" + speech.getAbsolutePath()});
logger.info("delivery Date summary played. waiting for DTMF ");
} catch (Exception e) {
logger.error("An unexpected exception occured while generating the deliveryDate tts file");
}
} else {
session.setAttribute("dateAndTime", dateAndTime);
}
}
}
| public static void updateDeliveryDate(SipSession session, String signal) {
int cause = -1;
try {
cause = Integer.parseInt(signal);
} catch (java.lang.NumberFormatException e) {
return;
}
synchronized(session) {
String dateAndTime = (String) session.getAttribute("dateAndTime");
if(dateAndTime == null) {
dateAndTime = "";
}
switch (cause) {
case Basic.CAUSE_DIGIT_0:
dateAndTime = dateAndTime + "0";
break;
case Basic.CAUSE_DIGIT_1:
dateAndTime = dateAndTime + "1";
break;
case Basic.CAUSE_DIGIT_2:
dateAndTime = dateAndTime + "2";
break;
case Basic.CAUSE_DIGIT_3:
dateAndTime = dateAndTime + "3";
break;
case Basic.CAUSE_DIGIT_4:
dateAndTime = dateAndTime + "4";
break;
case Basic.CAUSE_DIGIT_5:
dateAndTime = dateAndTime + "5";
break;
case Basic.CAUSE_DIGIT_6:
dateAndTime = dateAndTime + "6";
break;
case Basic.CAUSE_DIGIT_7:
dateAndTime = dateAndTime + "7";
break;
case Basic.CAUSE_DIGIT_8:
dateAndTime = dateAndTime + "8";
break;
case Basic.CAUSE_DIGIT_9:
dateAndTime = dateAndTime + "9";
break;
default:
break;
}
// TODO: Add logic to check if date and time is valid. We assume that
// user is well educated and will always punch right date and time
if (dateAndTime.length() == 10) {
char[] c = dateAndTime.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("You have selected delivery date to be ");
String date = "" + c[0] + c[1];
int iDate = (new Integer(date)).intValue();
stringBuffer.append(iDate);
String month = "" + c[2] + c[3];
int iMonth = (new Integer(month)).intValue();
String year = "" + c[4] + c[5];
int iYear = (new Integer(year)).intValue();
String hour = "" + c[6] + c[7];
int iHour = (new Integer(hour)).intValue();
String min = "" + c[8] + c[9];
int iMin = (new Integer(min)).intValue();
switch (iMonth) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
default:
break;
}
stringBuffer.append(" of ");
stringBuffer.append(month);
stringBuffer.append(" ");
stringBuffer.append(2000 + iYear);
stringBuffer.append(" at ");
stringBuffer.append(iHour);
stringBuffer.append(" hour and ");
stringBuffer.append(iMin);
stringBuffer.append(" minute. Thank you. Bye.");
java.sql.Timestamp timeStamp = new java.sql.Timestamp(
(iYear + 100), iMonth - 1, iDate, iHour, iMin, 0, 0);
try {
InitialContext ctx = new InitialContext();
OrderManager orderManager = (OrderManager) ctx.lookup("shopping-demo/OrderManagerBean/remote");
orderManager.setDeliveryDate(session.getApplicationSession().getAttribute("orderId"), timeStamp);
} catch (NamingException e) {
logger.error("An exception occured while retrieving the EJB OrderManager",e);
}
logger.info(stringBuffer.toString());
try {
TTSUtils.buildAudio(stringBuffer.toString(), "deliveryDate.wav");
MsConnection connection = (MsConnection) session.getApplicationSession().getAttribute("connection");
String endpoint = connection.getEndpoint();
MsSignalGenerator generator = connection.getSession().getProvider().getSignalGenerator(endpoint);
java.io.File speech = new File("deliveryDate.wav");
logger.info("Playing delivery date summary : " + "file://" + speech.getAbsolutePath());
MediaResourceListener mediaResourceListener = new MediaResourceListener(session, connection);
generator.addResourceListener(mediaResourceListener);
generator.apply(Announcement.PLAY, new String[]{"file://" + speech.getAbsolutePath()});
logger.info("delivery Date summary played. waiting for DTMF ");
} catch (Exception e) {
logger.error("An unexpected exception occured while generating the deliveryDate tts file");
}
} else {
session.setAttribute("dateAndTime", dateAndTime);
}
}
}
|
diff --git a/sources/android/java/com/template/android/BasicView.java b/sources/android/java/com/template/android/BasicView.java
index e6475a5..6f5880d 100644
--- a/sources/android/java/com/template/android/BasicView.java
+++ b/sources/android/java/com/template/android/BasicView.java
@@ -1,44 +1,44 @@
package com.template.android;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;
class BasicView extends GLSurfaceView {
public BasicView(Context context) {
super(context);
- setEGLConfigChooser(8, 8, 8, 8, 16, 0);
setEGLContextClientVersion(2);
+ setEGLConfigChooser(8, 8, 8, 8, 16, 8);
setPreserveEGLContextOnPause(true);
setRenderer(new Renderer());
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
NativeInterface.onTouchEvent(0, 0, 0, 0);
return true;
}
private static class Renderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 glUnused) {
NativeInterface.onDrawFrame();
}
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
NativeInterface.onSurfaceChanged(width, height);
}
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
NativeInterface.onSurfaceCreated();
}
}
}
| false | true | public BasicView(Context context) {
super(context);
setEGLConfigChooser(8, 8, 8, 8, 16, 0);
setEGLContextClientVersion(2);
setPreserveEGLContextOnPause(true);
setRenderer(new Renderer());
}
| public BasicView(Context context) {
super(context);
setEGLContextClientVersion(2);
setEGLConfigChooser(8, 8, 8, 8, 16, 8);
setPreserveEGLContextOnPause(true);
setRenderer(new Renderer());
}
|
diff --git a/src/com/android/launcher3/SavedWallpaperImages.java b/src/com/android/launcher3/SavedWallpaperImages.java
index afeea2df8..9766a8a23 100644
--- a/src/com/android/launcher3/SavedWallpaperImages.java
+++ b/src/com/android/launcher3/SavedWallpaperImages.java
@@ -1,187 +1,187 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.util.Pair;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class SavedWallpaperImages {
private static String TAG = "Launcher3.SavedWallpaperImages";
private ImageDb mDb;
ArrayList<Integer> mIds;
ArrayList<Drawable> mThumbs;
Context mContext;
public SavedWallpaperImages(Context context) {
mDb = new ImageDb(context);
mContext = context;
}
public void loadThumbnailsAndImageIdList() {
mIds = new ArrayList<Integer>();
mThumbs = new ArrayList<Drawable>();
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor result = db.query(ImageDb.TABLE_NAME,
new String[] { ImageDb.COLUMN_ID,
ImageDb.COLUMN_IMAGE_THUMBNAIL_FILENAME }, // cols to return
null, // select query
null, // args to select query
null,
null,
- null,
+ ImageDb.COLUMN_ID + " DESC",
null);
while (result.moveToNext()) {
String filename = result.getString(1);
File file = new File(mContext.getFilesDir(), filename);
Bitmap thumb = BitmapFactory.decodeFile(file.getAbsolutePath());
if (thumb != null) {
mIds.add(result.getInt(0));
mThumbs.add(new BitmapDrawable(thumb));
}
}
result.close();
}
public ArrayList<Drawable> getThumbnails() {
return mThumbs;
}
public ArrayList<Integer> getImageIds() {
return mIds;
}
public String getImageFilename(int id) {
Pair<String, String> filenames = getImageFilenames(id);
if (filenames != null) {
return filenames.second;
}
return null;
}
private Pair<String, String> getImageFilenames(int id) {
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor result = db.query(ImageDb.TABLE_NAME,
new String[] { ImageDb.COLUMN_IMAGE_THUMBNAIL_FILENAME,
ImageDb.COLUMN_IMAGE_FILENAME }, // cols to return
ImageDb.COLUMN_ID + " = ?", // select query
new String[] { Integer.toString(id) }, // args to select query
null,
null,
null,
null);
if (result.getCount() > 0) {
result.moveToFirst();
String thumbFilename = result.getString(0);
String imageFilename = result.getString(1);
result.close();
return new Pair<String, String>(thumbFilename, imageFilename);
} else {
return null;
}
}
public void deleteImage(int id) {
Pair<String, String> filenames = getImageFilenames(id);
File imageFile = new File(mContext.getFilesDir(), filenames.first);
imageFile.delete();
File thumbFile = new File(mContext.getFilesDir(), filenames.second);
thumbFile.delete();
SQLiteDatabase db = mDb.getWritableDatabase();
db.delete(ImageDb.TABLE_NAME,
ImageDb.COLUMN_ID + " = ?", // SELECT query
new String[] {
Integer.toString(id) // args to SELECT query
});
}
public void writeImage(Bitmap thumbnail, byte[] imageBytes) {
try {
File imageFile = File.createTempFile("wallpaper", "", mContext.getFilesDir());
FileOutputStream imageFileStream =
mContext.openFileOutput(imageFile.getName(), Context.MODE_PRIVATE);
imageFileStream.write(imageBytes);
imageFileStream.close();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 95, stream);
File thumbFile = File.createTempFile("wallpaperthumb", "", mContext.getFilesDir());
FileOutputStream thumbFileStream =
mContext.openFileOutput(thumbFile.getName(), Context.MODE_PRIVATE);
thumbFileStream.write(stream.toByteArray());
SQLiteDatabase db = mDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ImageDb.COLUMN_IMAGE_THUMBNAIL_FILENAME, thumbFile.getName());
values.put(ImageDb.COLUMN_IMAGE_FILENAME, imageFile.getName());
db.insert(ImageDb.TABLE_NAME, null, values);
} catch (IOException e) {
Log.e(TAG, "Failed writing images to storage " + e);
}
}
static class ImageDb extends SQLiteOpenHelper {
final static int DB_VERSION = 1;
final static String DB_NAME = "saved_wallpaper_images.db";
final static String TABLE_NAME = "saved_wallpaper_images";
final static String COLUMN_ID = "id";
final static String COLUMN_IMAGE_THUMBNAIL_FILENAME = "image_thumbnail";
final static String COLUMN_IMAGE_FILENAME = "image";
Context mContext;
public ImageDb(Context context) {
super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
// Store the context for later use
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER NOT NULL, " +
COLUMN_IMAGE_THUMBNAIL_FILENAME + " TEXT NOT NULL, " +
COLUMN_IMAGE_FILENAME + " TEXT NOT NULL, " +
"PRIMARY KEY (" + COLUMN_ID + " ASC) " +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Delete all the records; they'll be repopulated as this is a cache
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
}
}
| true | true | public void loadThumbnailsAndImageIdList() {
mIds = new ArrayList<Integer>();
mThumbs = new ArrayList<Drawable>();
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor result = db.query(ImageDb.TABLE_NAME,
new String[] { ImageDb.COLUMN_ID,
ImageDb.COLUMN_IMAGE_THUMBNAIL_FILENAME }, // cols to return
null, // select query
null, // args to select query
null,
null,
null,
null);
while (result.moveToNext()) {
String filename = result.getString(1);
File file = new File(mContext.getFilesDir(), filename);
Bitmap thumb = BitmapFactory.decodeFile(file.getAbsolutePath());
if (thumb != null) {
mIds.add(result.getInt(0));
mThumbs.add(new BitmapDrawable(thumb));
}
}
result.close();
}
| public void loadThumbnailsAndImageIdList() {
mIds = new ArrayList<Integer>();
mThumbs = new ArrayList<Drawable>();
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor result = db.query(ImageDb.TABLE_NAME,
new String[] { ImageDb.COLUMN_ID,
ImageDb.COLUMN_IMAGE_THUMBNAIL_FILENAME }, // cols to return
null, // select query
null, // args to select query
null,
null,
ImageDb.COLUMN_ID + " DESC",
null);
while (result.moveToNext()) {
String filename = result.getString(1);
File file = new File(mContext.getFilesDir(), filename);
Bitmap thumb = BitmapFactory.decodeFile(file.getAbsolutePath());
if (thumb != null) {
mIds.add(result.getInt(0));
mThumbs.add(new BitmapDrawable(thumb));
}
}
result.close();
}
|
diff --git a/src/main/java/goldengate/commandexec/server/LocalExecServerHandler.java b/src/main/java/goldengate/commandexec/server/LocalExecServerHandler.java
index e696f88..b5b0be4 100644
--- a/src/main/java/goldengate/commandexec/server/LocalExecServerHandler.java
+++ b/src/main/java/goldengate/commandexec/server/LocalExecServerHandler.java
@@ -1,381 +1,381 @@
/**
* Copyright 2009, Frederic Bregier, and individual contributors by the @author
* tags. See the COPYRIGHT.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3.0 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package goldengate.commandexec.server;
import goldengate.commandexec.utils.LocalExecDefaultResult;
import goldengate.common.logging.GgInternalLogger;
import goldengate.common.logging.GgInternalLoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.RejectedExecutionException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
/**
* Handles a server-side channel for LocalExec.
*
*
*/
public class LocalExecServerHandler extends SimpleChannelUpstreamHandler {
// Fixed delay, but could change if necessary at construction
private long delay = LocalExecDefaultResult.MAXWAITPROCESS;
protected LocalExecServerPipelineFactory factory = null;
static protected boolean isShutdown = false;
/**
* Internal Logger
*/
private static final GgInternalLogger logger = GgInternalLoggerFactory
.getLogger(LocalExecServerHandler.class);
protected boolean answered = false;
/**
* Is the Local Exec Server going Shutdown
* @param channel associated channel
* @return True if in Shutdown
*/
public static boolean isShutdown(Channel channel) {
if (isShutdown) {
channel.write(LocalExecDefaultResult.ConnectionRefused.result);
channel.write(LocalExecDefaultResult.ENDOFCOMMAND).awaitUninterruptibly();
Channels.close(channel);
return true;
}
return false;
}
/**
* Print stack trace
* @param thread
* @param stacks
*/
static private void printStackTrace(Thread thread, StackTraceElement[] stacks) {
System.err.print(thread.toString() + " : ");
for (int i = 0; i < stacks.length-1; i++) {
System.err.print(stacks[i].toString()+" ");
}
System.err.println(stacks[stacks.length-1].toString());
}
/**
* Shutdown thread
* @author Frederic Bregier
*
*/
private static class GGLEThreadShutdown extends Thread {
long delay = 3000;
LocalExecServerPipelineFactory factory;
public GGLEThreadShutdown(LocalExecServerPipelineFactory factory) {
this.factory = factory;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Timer timer = null;
timer = new Timer(true);
GGLETimerTask ggleTimerTask = new GGLETimerTask();
timer.schedule(ggleTimerTask, delay);
factory.releaseResources();
System.exit(0);
}
}
/**
* TimerTask to terminate the server
* @author Frederic Bregier
*
*/
private static class GGLETimerTask extends TimerTask {
/**
* Internal Logger
*/
private static final GgInternalLogger logger = GgInternalLoggerFactory
.getLogger(GGLETimerTask.class);
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
logger.error("System will force EXIT");
Map<Thread, StackTraceElement[]> map = Thread
.getAllStackTraces();
for (Thread thread: map.keySet()) {
printStackTrace(thread, map.get(thread));
}
System.exit(0);
}
}
/**
* Constructor with a specific delay
* @param newdelay
*/
public LocalExecServerHandler(LocalExecServerPipelineFactory factory, long newdelay) {
this.factory = factory;
delay = newdelay;
}
/* (non-Javadoc)
* @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelConnected(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent)
*/
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
if (isShutdown(ctx.getChannel())) {
answered = true;
return;
}
answered = false;
factory.addChannel(ctx.getChannel());
}
/* (non-Javadoc)
* @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelDisconnected(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent)
*/
@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
this.factory.removeChannel(e.getChannel());
}
/**
* Change the delay to the specific value. Need to be called before any receive message.
* @param newdelay
*/
public void setNewDelay(long newdelay) {
delay = newdelay;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent evt) {
answered = false;
// Cast to a String first.
// We know it is a String because we put some codec in
// LocalExecPipelineFactory.
String request = (String) evt.getMessage();
// Generate and write a response.
String response;
response = LocalExecDefaultResult.NoStatus.status+" "+
LocalExecDefaultResult.NoStatus.result;
boolean isLocallyShutdown = false;
ExecuteWatchdog watchdog = null;
try {
if (request.length() == 0) {
// No command
response = LocalExecDefaultResult.NoCommand.status+" "+
LocalExecDefaultResult.NoCommand.result;
} else {
String[] args = request.split(" ");
int cpt = 0;
long tempDelay;
try {
tempDelay = Long.parseLong(args[0]);
cpt++;
} catch (NumberFormatException e) {
tempDelay = delay;
}
if (tempDelay < 0) {
// Shutdown Order
isShutdown = true;
logger.warn("Shutdown order received");
isLocallyShutdown = isShutdown(evt.getChannel());
// Wait the specified time
try {
Thread.sleep(-tempDelay);
} catch (InterruptedException e) {
}
Thread thread = new GGLEThreadShutdown(factory);
thread.start();
return;
}
String binary = args[cpt++];
File exec = new File(binary);
if (exec.isAbsolute()) {
// If true file, is it executable
if (! exec.canExecute()) {
logger.error("Exec command is not executable: " + request);
response = LocalExecDefaultResult.NotExecutable.status+" "+
LocalExecDefaultResult.NotExecutable.result;
return;
}
}
// Create command with parameters
CommandLine commandLine = new CommandLine(binary);
for (; cpt < args.length; cpt ++) {
commandLine.addArgument(args[cpt]);
}
DefaultExecutor defaultExecutor = new DefaultExecutor();
ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
defaultExecutor.setStreamHandler(pumpStreamHandler);
int[] correctValues = { 0, 1 };
defaultExecutor.setExitValues(correctValues);
if (tempDelay > 0) {
// If delay (max time), then setup Watchdog
watchdog = new ExecuteWatchdog(tempDelay);
defaultExecutor.setWatchdog(watchdog);
}
int status = -1;
try {
// Execute the command
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e) {
if (e.getExitValue() == -559038737) {
// Cannot run immediately so retry once
try {
Thread.sleep(LocalExecDefaultResult.RETRYINMS);
} catch (InterruptedException e1) {
}
try {
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
} catch (IOException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} else {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} catch (IOException e) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
pumpStreamHandler.stop();
if (defaultExecutor.isFailure(status) && watchdog != null &&
watchdog.killedProcess()) {
// kill by the watchdoc (time out)
logger.error("Exec is in Time Out");
response = LocalExecDefaultResult.TimeOutExecution.status+" "+
LocalExecDefaultResult.TimeOutExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
} else {
response = status+" "+outputStream.toString();
try {
outputStream.close();
} catch (IOException e2) {
}
}
}
} finally {
if (isLocallyShutdown) {
return;
}
// We do not need to write a ChannelBuffer here.
// We know the encoder inserted at LocalExecPipelineFactory will do the
// conversion.
evt.getChannel().write(response+"\n");
answered = true;
if (watchdog != null) {
watchdog.stop();
}
- logger.warn("End of Command: "+request+" : "+response);
+ logger.info("End of Command: "+request+" : "+response);
evt.getChannel().write(LocalExecDefaultResult.ENDOFCOMMAND);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (answered) {
logger.debug("Exception while answered: ",e.getCause());
} else {
logger.error("Unexpected exception from downstream while not answered.", e
.getCause());
}
Throwable e1 = e.getCause();
// Look if Nothing to do since execution will stop later on and
// an error will occur on client side
// since no message arrived before close (or partially)
if (e1 instanceof CancelledKeyException) {
} else if (e1 instanceof ClosedChannelException) {
} else if (e1 instanceof NullPointerException) {
if (e.getChannel().isConnected()) {
e.getChannel().close();
}
} else if (e1 instanceof IOException) {
if (e.getChannel().isConnected()) {
e.getChannel().close();
}
} else if (e1 instanceof RejectedExecutionException) {
if (e.getChannel().isConnected()) {
e.getChannel().close();
}
}
}
}
| true | true | public void messageReceived(ChannelHandlerContext ctx, MessageEvent evt) {
answered = false;
// Cast to a String first.
// We know it is a String because we put some codec in
// LocalExecPipelineFactory.
String request = (String) evt.getMessage();
// Generate and write a response.
String response;
response = LocalExecDefaultResult.NoStatus.status+" "+
LocalExecDefaultResult.NoStatus.result;
boolean isLocallyShutdown = false;
ExecuteWatchdog watchdog = null;
try {
if (request.length() == 0) {
// No command
response = LocalExecDefaultResult.NoCommand.status+" "+
LocalExecDefaultResult.NoCommand.result;
} else {
String[] args = request.split(" ");
int cpt = 0;
long tempDelay;
try {
tempDelay = Long.parseLong(args[0]);
cpt++;
} catch (NumberFormatException e) {
tempDelay = delay;
}
if (tempDelay < 0) {
// Shutdown Order
isShutdown = true;
logger.warn("Shutdown order received");
isLocallyShutdown = isShutdown(evt.getChannel());
// Wait the specified time
try {
Thread.sleep(-tempDelay);
} catch (InterruptedException e) {
}
Thread thread = new GGLEThreadShutdown(factory);
thread.start();
return;
}
String binary = args[cpt++];
File exec = new File(binary);
if (exec.isAbsolute()) {
// If true file, is it executable
if (! exec.canExecute()) {
logger.error("Exec command is not executable: " + request);
response = LocalExecDefaultResult.NotExecutable.status+" "+
LocalExecDefaultResult.NotExecutable.result;
return;
}
}
// Create command with parameters
CommandLine commandLine = new CommandLine(binary);
for (; cpt < args.length; cpt ++) {
commandLine.addArgument(args[cpt]);
}
DefaultExecutor defaultExecutor = new DefaultExecutor();
ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
defaultExecutor.setStreamHandler(pumpStreamHandler);
int[] correctValues = { 0, 1 };
defaultExecutor.setExitValues(correctValues);
if (tempDelay > 0) {
// If delay (max time), then setup Watchdog
watchdog = new ExecuteWatchdog(tempDelay);
defaultExecutor.setWatchdog(watchdog);
}
int status = -1;
try {
// Execute the command
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e) {
if (e.getExitValue() == -559038737) {
// Cannot run immediately so retry once
try {
Thread.sleep(LocalExecDefaultResult.RETRYINMS);
} catch (InterruptedException e1) {
}
try {
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
} catch (IOException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} else {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} catch (IOException e) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
pumpStreamHandler.stop();
if (defaultExecutor.isFailure(status) && watchdog != null &&
watchdog.killedProcess()) {
// kill by the watchdoc (time out)
logger.error("Exec is in Time Out");
response = LocalExecDefaultResult.TimeOutExecution.status+" "+
LocalExecDefaultResult.TimeOutExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
} else {
response = status+" "+outputStream.toString();
try {
outputStream.close();
} catch (IOException e2) {
}
}
}
} finally {
if (isLocallyShutdown) {
return;
}
// We do not need to write a ChannelBuffer here.
// We know the encoder inserted at LocalExecPipelineFactory will do the
// conversion.
evt.getChannel().write(response+"\n");
answered = true;
if (watchdog != null) {
watchdog.stop();
}
logger.warn("End of Command: "+request+" : "+response);
evt.getChannel().write(LocalExecDefaultResult.ENDOFCOMMAND);
}
}
| public void messageReceived(ChannelHandlerContext ctx, MessageEvent evt) {
answered = false;
// Cast to a String first.
// We know it is a String because we put some codec in
// LocalExecPipelineFactory.
String request = (String) evt.getMessage();
// Generate and write a response.
String response;
response = LocalExecDefaultResult.NoStatus.status+" "+
LocalExecDefaultResult.NoStatus.result;
boolean isLocallyShutdown = false;
ExecuteWatchdog watchdog = null;
try {
if (request.length() == 0) {
// No command
response = LocalExecDefaultResult.NoCommand.status+" "+
LocalExecDefaultResult.NoCommand.result;
} else {
String[] args = request.split(" ");
int cpt = 0;
long tempDelay;
try {
tempDelay = Long.parseLong(args[0]);
cpt++;
} catch (NumberFormatException e) {
tempDelay = delay;
}
if (tempDelay < 0) {
// Shutdown Order
isShutdown = true;
logger.warn("Shutdown order received");
isLocallyShutdown = isShutdown(evt.getChannel());
// Wait the specified time
try {
Thread.sleep(-tempDelay);
} catch (InterruptedException e) {
}
Thread thread = new GGLEThreadShutdown(factory);
thread.start();
return;
}
String binary = args[cpt++];
File exec = new File(binary);
if (exec.isAbsolute()) {
// If true file, is it executable
if (! exec.canExecute()) {
logger.error("Exec command is not executable: " + request);
response = LocalExecDefaultResult.NotExecutable.status+" "+
LocalExecDefaultResult.NotExecutable.result;
return;
}
}
// Create command with parameters
CommandLine commandLine = new CommandLine(binary);
for (; cpt < args.length; cpt ++) {
commandLine.addArgument(args[cpt]);
}
DefaultExecutor defaultExecutor = new DefaultExecutor();
ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
defaultExecutor.setStreamHandler(pumpStreamHandler);
int[] correctValues = { 0, 1 };
defaultExecutor.setExitValues(correctValues);
if (tempDelay > 0) {
// If delay (max time), then setup Watchdog
watchdog = new ExecuteWatchdog(tempDelay);
defaultExecutor.setWatchdog(watchdog);
}
int status = -1;
try {
// Execute the command
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e) {
if (e.getExitValue() == -559038737) {
// Cannot run immediately so retry once
try {
Thread.sleep(LocalExecDefaultResult.RETRYINMS);
} catch (InterruptedException e1) {
}
try {
status = defaultExecutor.execute(commandLine);
} catch (ExecuteException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
} catch (IOException e1) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} else {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
} catch (IOException e) {
pumpStreamHandler.stop();
logger.error("Exception: " + e.getMessage() +
" Exec in error with " + commandLine.toString());
response = LocalExecDefaultResult.BadExecution.status+" "+
LocalExecDefaultResult.BadExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
return;
}
pumpStreamHandler.stop();
if (defaultExecutor.isFailure(status) && watchdog != null &&
watchdog.killedProcess()) {
// kill by the watchdoc (time out)
logger.error("Exec is in Time Out");
response = LocalExecDefaultResult.TimeOutExecution.status+" "+
LocalExecDefaultResult.TimeOutExecution.result;
try {
outputStream.close();
} catch (IOException e2) {
}
} else {
response = status+" "+outputStream.toString();
try {
outputStream.close();
} catch (IOException e2) {
}
}
}
} finally {
if (isLocallyShutdown) {
return;
}
// We do not need to write a ChannelBuffer here.
// We know the encoder inserted at LocalExecPipelineFactory will do the
// conversion.
evt.getChannel().write(response+"\n");
answered = true;
if (watchdog != null) {
watchdog.stop();
}
logger.info("End of Command: "+request+" : "+response);
evt.getChannel().write(LocalExecDefaultResult.ENDOFCOMMAND);
}
}
|
diff --git a/cdi/plugins/org.jboss.tools.cdi.seam.core/src/org/jboss/tools/cdi/seam/core/international/el/CDIInternationalMessagesELResolver.java b/cdi/plugins/org.jboss.tools.cdi.seam.core/src/org/jboss/tools/cdi/seam/core/international/el/CDIInternationalMessagesELResolver.java
index bac66b9b5..24fa5d7ab 100644
--- a/cdi/plugins/org.jboss.tools.cdi.seam.core/src/org/jboss/tools/cdi/seam/core/international/el/CDIInternationalMessagesELResolver.java
+++ b/cdi/plugins/org.jboss.tools.cdi.seam.core/src/org/jboss/tools/cdi/seam/core/international/el/CDIInternationalMessagesELResolver.java
@@ -1,677 +1,687 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributor:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.seam.core.international.el;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.graphics.Image;
import org.jboss.tools.cdi.core.CDICorePlugin;
import org.jboss.tools.cdi.seam.core.CDISeamCorePlugin;
import org.jboss.tools.cdi.seam.core.international.BundleModelFactory;
import org.jboss.tools.cdi.seam.core.international.IBundle;
import org.jboss.tools.cdi.seam.core.international.IBundleModel;
import org.jboss.tools.cdi.seam.core.international.IProperty;
import org.jboss.tools.cdi.seam.core.international.impl.BundleImpl;
import org.jboss.tools.cdi.seam.core.international.impl.LocalizedValue;
import org.jboss.tools.cdi.seam.core.international.impl.PropertyImpl;
import org.jboss.tools.common.el.core.ca.AbstractELCompletionEngine;
import org.jboss.tools.common.el.core.model.ELArgumentInvocation;
import org.jboss.tools.common.el.core.model.ELExpression;
import org.jboss.tools.common.el.core.model.ELInstance;
import org.jboss.tools.common.el.core.model.ELInvocationExpression;
import org.jboss.tools.common.el.core.model.ELModel;
import org.jboss.tools.common.el.core.model.ELObjectType;
import org.jboss.tools.common.el.core.model.ELPropertyInvocation;
import org.jboss.tools.common.el.core.parser.ELParser;
import org.jboss.tools.common.el.core.parser.ELParserFactory;
import org.jboss.tools.common.el.core.parser.ELParserUtil;
import org.jboss.tools.common.el.core.parser.LexicalToken;
import org.jboss.tools.common.el.core.resolver.ELContext;
import org.jboss.tools.common.el.core.resolver.ELResolution;
import org.jboss.tools.common.el.core.resolver.ELResolutionImpl;
import org.jboss.tools.common.el.core.resolver.ELSegmentImpl;
import org.jboss.tools.common.el.core.resolver.IRelevanceCheck;
import org.jboss.tools.common.el.core.resolver.IVariable;
import org.jboss.tools.common.el.core.resolver.MessagePropertyELSegmentImpl;
import org.jboss.tools.common.el.core.resolver.TypeInfoCollector.MemberInfo;
import org.jboss.tools.common.model.XModelObject;
import org.jboss.tools.common.model.util.PositionHolder;
import org.jboss.tools.common.text.TextProposal;
import org.jboss.tools.jst.web.kb.IPageContext;
import org.jboss.tools.jst.web.kb.IResourceBundle;
import org.jboss.tools.jst.web.kb.internal.ResourceBundle;
/**
*
* @author Victor V. Rubezhny
*
*/
public class CDIInternationalMessagesELResolver extends AbstractELCompletionEngine<IVariable> {
private static final Image CDI_INTERNATIONAL_MESSAGE_PROPOSAL_IMAGE =
CDISeamCorePlugin.getDefault().getImage(CDISeamCorePlugin.CA_CDI_MESSAGE_IMAGE_PATH);
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.ca.AbstractELCompletionEngine#getELProposalImage()
*/
public Image getELProposalImage() {
return CDI_INTERNATIONAL_MESSAGE_PROPOSAL_IMAGE;
}
private static ELParserFactory factory = ELParserUtil.getDefaultFactory();
public CDIInternationalMessagesELResolver() {}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.resolver.ELResolver#getParserFactory()
*/
public ELParserFactory getParserFactory() {
return factory;
}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.ca.AbstractELCompletionEngine#log(java.lang.Exception)
*/
protected void log(Exception e) {
CDISeamCorePlugin.getDefault().logError(e);
}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.resolver.ELResolver2#getProposals(org.jboss.tools.common.el.core.resolver.ELContext, java.lang.String)
*/
public List<TextProposal> getProposals(ELContext context, String el, int offset) {
return getCompletions(el, false, 0, context);
}
public List<TextProposal> getCompletions(String elString,
boolean returnEqualedVariablesOnly, int position, ELContext context) {
IProject project = context == null ? null :
context.getResource() == null ? null :
context.getResource().getProject();
if (project == null)
return null;
if (!CDICorePlugin.getCDI(project, true).getExtensionManager().isCDIExtensionAvailable(CDISeamCorePlugin.CDI_INTERNATIONAL_RUNTIME_EXTENTION))
return null;
IBundleModel bundleModel = BundleModelFactory.getBundleModel(project);
if (bundleModel == null)
return null;
IResourceBundle[] bundles = findResourceBundles(bundleModel);
IDocument document = null;
if (bundles == null)
bundles = new IResourceBundle[0];
List<TextProposal> proposals = null;
try {
proposals = getCompletions(context.getResource(), document, elString.subSequence(0, elString.length()), position, returnEqualedVariablesOnly, bundles);
} catch (StringIndexOutOfBoundsException e) {
log(e);
} catch (BadLocationException e) {
log(e);
}
return proposals;
}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.resolver.ELResolver2#resolve(org.jboss.tools.common.el.core.resolver.ELContext, org.jboss.tools.common.el.core.model.ELExpression)
*/
public ELResolution resolve(ELContext context, ELExpression operand, int offset) {
ELResolutionImpl resolution = resolveELOperand(operand, context, true);
if(resolution != null)
resolution.setContext(context);
return resolution;
}
public ELResolutionImpl resolveELOperand(ELExpression operand,
ELContext context, boolean returnEqualedVariablesOnly) {
IResourceBundle[] bundles = new IResourceBundle[0];
if(context instanceof IPageContext) {
IBundleModel bundleModel = BundleModelFactory.getBundleModel(context.getResource().getProject());
if (bundleModel != null) {
bundles = findResourceBundles(bundleModel);
}
}
try {
return resolveELOperand(context.getResource(), operand, returnEqualedVariablesOnly, bundles);
} catch (StringIndexOutOfBoundsException e) {
log(e);
} catch (BadLocationException e) {
log(e);
}
return null;
}
public List<TextProposal> getCompletions(IFile file, IDocument document, CharSequence prefix,
int position, boolean returnEqualedVariablesOnly, IResourceBundle[] bundles) throws BadLocationException, StringIndexOutOfBoundsException {
List<TextProposal> completions = new ArrayList<TextProposal>();
ELResolutionImpl status = resolveELOperand(file, parseOperand("" + prefix), returnEqualedVariablesOnly, bundles); //$NON-NLS-1$
if(status!=null) {
completions.addAll(status.getProposals());
}
return completions;
}
public ELExpression parseOperand(String operand) {
if(operand == null) return null;
String el = (operand.indexOf("#{") < 0 && operand.indexOf("${") < 0) ? "#{" + operand + "}" : operand; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
ELParser p = getParserFactory().createParser();
ELModel model = p.parse(el);
List<ELInstance> is = model.getInstances();
if(is.isEmpty()) return null;
return is.get(0).getExpression();
}
public ELResolutionImpl resolveELOperand(IFile file,
ELExpression operand, boolean returnEqualedVariablesOnly, IResourceBundle[] bundles)
throws BadLocationException, StringIndexOutOfBoundsException {
if(!(operand instanceof ELInvocationExpression) || file == null) {
return null;
}
ELInvocationExpression expr = (ELInvocationExpression)operand;
boolean isIncomplete = expr.getType() == ELObjectType.EL_PROPERTY_INVOCATION
&& ((ELPropertyInvocation)expr).getName() == null;
boolean isArgument = expr.getType() == ELObjectType.EL_ARGUMENT_INVOCATION;
ELResolutionImpl resolution = new ELResolutionImpl(expr);
ELInvocationExpression left = expr;
List<Variable> resolvedVariables = new ArrayList<Variable>();
if (expr.getLeft() != null && isArgument) {
left = expr.getLeft();
resolvedVariables = resolveVariables(file, left, bundles, false,
true); // is Final and equal names are because of
// we have no more to resolve the parts of expression,
// but we have to resolve arguments of probably a message component
if (resolvedVariables != null && !resolvedVariables.isEmpty()) {
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVariables) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
}
} else if (expr.getLeft() == null && isIncomplete) {
resolvedVariables = resolveVariables(file, expr, bundles, true,
returnEqualedVariablesOnly);
} else {
while(left != null) {
List<Variable>resolvedVars = new ArrayList<Variable>();
resolvedVars = resolveVariables(file,
left, bundles, left == expr,
returnEqualedVariablesOnly);
if (resolvedVars != null && !resolvedVars.isEmpty()) {
resolvedVariables = resolvedVars;
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVars) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
+ if(left.getLastToken() != left.getFirstToken()) {
+ LexicalToken combined = left.getFirstToken().getNextToken().getCombinedToken(left.getLastToken());
+ segment = new MessagePropertyELSegmentImpl(combined);
+ processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
+ segment.setResolved(true);
+ for (Variable variable : resolvedVars) {
+ segment.getVariables().add(variable);
+ }
+ resolution.addSegment(segment);
+ }
break;
}
left = (ELInvocationExpression)left.getLeft();
}
}
if (resolution.getLastResolvedToken() == null &&
!returnEqualedVariablesOnly &&
expr != null &&
isIncomplete) {
// no vars are resolved
// the tokens are the part of var name ended with a separator (.)
resolvedVariables = resolveVariables(file, expr, bundles, true, returnEqualedVariablesOnly);
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
if (left != null) {
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(false);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(varName.startsWith(operand.getText())) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
setImage(proposal);
proposals.add(proposal);
}
}
resolution.setProposals(proposals);
segment.setResolved(!proposals.isEmpty());
}
return resolution;
}
// Here we have a list of vars for some part of expression
// OK. we'll proceed with members of these vars
if (resolution.getLastResolvedToken() == operand) {
// First segment is the last one
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
ELSegmentImpl segment = new ELSegmentImpl(operand.getFirstToken());
segment.setResolved(true);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(operand.getLength()<=varName.length()) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
} else if(returnEqualedVariablesOnly) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName);
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
}
segment.getVariables().add(var);
}
resolution.setLastResolvedToken(expr);
resolution.setProposals(proposals);
return resolution;
}
//process segments one by one
if(left != null) {
while(left != expr) {
left = (ELInvocationExpression)left.getParent();
if (left != expr) { // inside expression
ELSegmentImpl segment = new ELSegmentImpl(left.getLastToken());
segment.setResolved(true);
resolution.addSegment(segment);
resolution.setLastResolvedToken(left);
return resolution;
} else { // Last segment
resolveLastSegment((ELInvocationExpression)operand, resolvedVariables, resolution, returnEqualedVariablesOnly);
break;
}
}
} else {
ELSegmentImpl segment = new ELSegmentImpl(expr.getFirstToken());
resolution.addSegment(segment);
}
return resolution;
}
public List<Variable> resolveVariables(IFile file, ELInvocationExpression expr, IResourceBundle[] bundles, boolean isFinal, boolean onlyEqualNames) {
List<Variable> result = new ArrayList<Variable>();
String varName = expr.toString();
for (IResourceBundle b: bundles) {
String name = b.getVar();
if(!isFinal || onlyEqualNames) {
if(!name.equals(varName)) continue;
}
if(!name.startsWith(varName)) continue;
Variable v = new Variable(name, b.getBasename(), file);
result.add(v);
}
return result;
}
protected void setImage(TextProposal kbProposal) {
kbProposal.setImage(getELProposalImage());
}
protected void resolveLastSegment(ELInvocationExpression expr,
List<Variable> members,
ELResolutionImpl resolution,
boolean returnEqualedVariablesOnly) {
Set<TextProposal> kbProposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
ELSegmentImpl segment = new ELSegmentImpl(expr.getFirstToken());
resolution.setProposals(kbProposals);
if(expr instanceof ELPropertyInvocation) {
segment = new MessagePropertyELSegmentImpl(((ELPropertyInvocation)expr).getName());
processMessagePropertySegment(expr, (MessagePropertyELSegmentImpl)segment, members);
} else if (expr instanceof ELArgumentInvocation) {
segment = new MessagePropertyELSegmentImpl(((ELArgumentInvocation)expr).getArgument().getOpenArgumentToken().getNextToken());
processMessagePropertySegment(expr, (MessagePropertyELSegmentImpl)segment, members);
}
if(segment.getToken()!=null) {
resolution.addSegment(segment);
}
if (expr.getType() == ELObjectType.EL_PROPERTY_INVOCATION && ((ELPropertyInvocation)expr).getName() == null) {
// return all the methods + properties
for (Variable mbr : members) {
processSingularMember(mbr, kbProposals);
}
} else
if(expr.getType() != ELObjectType.EL_ARGUMENT_INVOCATION) {
Set<String> proposalsToFilter = new TreeSet<String>();
for (Variable mbr : members) {
filterSingularMember(mbr, proposalsToFilter);
}
for (String proposal : proposalsToFilter) {
// We do expect nothing but name for method tokens (No round brackets)
String filter = expr.getMemberName();
if(filter == null) filter = ""; //$NON-NLS-1$
if(returnEqualedVariablesOnly) {
// This is used for validation.
if (proposal.equals(filter)) {
TextProposal kbProposal = new TextProposal();
kbProposal.setReplacementString(proposal);
kbProposal.setLabel(proposal);
setImage(kbProposal);
kbProposals.add(kbProposal);
break;
}
} else if (proposal.startsWith(filter)) {
// This is used for CA.
TextProposal kbProposal = new TextProposal();
kbProposal.setReplacementString(proposal.substring(filter.length()));
kbProposal.setLabel(proposal);
kbProposal.setImage(getELProposalImage());
kbProposals.add(kbProposal);
}
}
} else if(expr.getType() == ELObjectType.EL_ARGUMENT_INVOCATION) {
Set<String> proposalsToFilter = new TreeSet<String>();
boolean isMessages = false;
for (Variable mbr : members) {
isMessages = true;
filterSingularMember(mbr, proposalsToFilter);
}
String filter = expr.getMemberName();
boolean bSurroundWithQuotes = false;
if(filter == null) {
filter = ""; //$NON-NLS-1$
bSurroundWithQuotes = true;
} else {
boolean b = filter.startsWith("'") || filter.startsWith("\""); //$NON-NLS-1$ //$NON-NLS-2$
boolean e = filter.endsWith("'") || filter.endsWith("\""); //$NON-NLS-1$ //$NON-NLS-2$
if((b) && (e)) {
filter = filter.length() == 1 ? "" : filter.substring(1, filter.length() - 1); //$NON-NLS-1$
} else if(b && !returnEqualedVariablesOnly) {
filter = filter.substring(1);
} else {
//Value is set as expression itself, we cannot compute it
if(isMessages) {
resolution.setMapOrCollectionOrBundleAmoungTheTokens(true);
}
return;
}
}
for (String proposal : proposalsToFilter) {
if(returnEqualedVariablesOnly) {
// This is used for validation.
if (proposal.equals(filter)) {
TextProposal kbProposal = new TextProposal();
kbProposal.setReplacementString(proposal);
kbProposal.setLabel(proposal);
setImage(kbProposal);
kbProposals.add(kbProposal);
break;
}
} else if (proposal.startsWith(filter)) {
// This is used for CA.
TextProposal kbProposal = new TextProposal();
String replacementString = proposal.substring(filter.length());
if (bSurroundWithQuotes) {
replacementString = "'" + replacementString + "']"; //$NON-NLS-1$ //$NON-NLS-2$
}
kbProposal.setReplacementString(replacementString);
kbProposal.setLabel(proposal);
kbProposal.setImage(getELProposalImage());
kbProposals.add(kbProposal);
}
}
}
segment.setResolved(!kbProposals.isEmpty());
if (resolution.isResolved()){
resolution.setLastResolvedToken(expr);
}
}
private void processMessageBundleSegment(ELInvocationExpression expr, MessagePropertyELSegmentImpl segment, List<Variable> variables) {
if(segment.getToken() == null)
return;
for(Variable variable : variables){
if(isRelevant(expr, variable)) {
IBundleModel bundleModel = BundleModelFactory.getBundleModel(variable.f.getProject());
if(bundleModel == null) return;
if(bundleModel.getBundle(variable.basename) == null)
return;
segment.setBaseName(variable.basename);
segment.setBundleOnlySegment(true);
IBundle bundle = bundleModel.getBundle(variable.basename);
if(bundle == null)
continue;
Map<String, XModelObject> os = ((BundleImpl)bundle).getObjects();
for (XModelObject o: os.values()) {
segment.addObject(o);
}
}
}
}
/*
* Checks that name of variable is equal to the beginning of expression, which can take more than one token (like a.b.c)
*/
private boolean isRelevant(ELInvocationExpression expr, Variable variable) {
LexicalToken t = expr.getFirstToken();
StringBuffer sb = new StringBuffer();
sb.append(t.getText());
boolean ok = sb.toString().equals(variable.name);
while(!ok && t != null && t != expr.getLastToken()) {
t = t.getNextToken();
sb.append(t.getText());
ok = sb.toString().equals(variable.name);
}
return ok;
}
private void processMessagePropertySegment(ELInvocationExpression expr, MessagePropertyELSegmentImpl segment, List<Variable> variables){
if(segment.getToken() == null)
return;
for(Variable variable : variables){
if(isRelevant(expr, variable)) {
IBundleModel bundleModel = BundleModelFactory.getBundleModel(variable.f.getProject());
if(bundleModel == null) return;
IBundle bundle = bundleModel.getBundle(variable.basename);
if(bundle == null)
return;
String propertyName = segment.getToken().getText();
IProperty prop = bundle.getProperty(propertyName);
if(prop == null) continue;
Map<String, LocalizedValue> values = ((PropertyImpl)prop).getValues();
for (LocalizedValue value: values.values()) {
XModelObject p = value.getObject();
segment.addObject(p);
segment.setBaseName(variable.basename);
PositionHolder h = PositionHolder.getPosition(p, null);
h.update();
segment.setMessagePropertySourceReference(h.getStart(), prop.getName().length());
IFile propFile = (IFile)p.getAdapter(IFile.class);
if(propFile == null)
continue;
segment.setMessageBundleResource(propFile);
}
}
}
}
public boolean findPropertyLocation(XModelObject property, String content, MessagePropertyELSegmentImpl segment) {
String name = property.getAttributeValue("name"); //$NON-NLS-1$
String nvs = property.getAttributeValue("name-value-separator"); //$NON-NLS-1$
int i = content.indexOf(name + nvs);
if(i < 0) return false;
segment.setMessagePropertySourceReference(i, name.length());
return true;
}
protected void processSingularMember(Variable mbr, Set<TextProposal> kbProposals) {
// Surround the "long" keys containing the dots with [' ']
TreeSet<String> keys = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
keys.addAll(mbr.getKeys());
Iterator<String> sortedKeys = keys.iterator();
while(sortedKeys.hasNext()) {
String key = sortedKeys.next();
if (key == null || key.length() == 0)
continue;
if (key.indexOf('.') != -1) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString("['" + key + "']"); //$NON-NLS-1$ //$NON-NLS-2$
proposal.setLabel("['" + key + "']");
setImage(proposal);
kbProposals.add(proposal);
} else {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(key);
proposal.setLabel(key);
setImage(proposal);
kbProposals.add(proposal);
}
}
}
protected void filterSingularMember(Variable mbr, Set<String> proposalsToFilter) {
Collection<String> keys = mbr.getKeys();
for (String key : keys) {
proposalsToFilter.add(key);
}
}
static class Variable implements IVariable {
IFile f;
String name;
String basename;
public Variable(String name, String basename, IFile f) {
this.name = name;
this.basename = basename;
this.f = f;
}
public String getName() {
return name;
}
public String getBasename() {
return basename;
}
public Collection<String> getKeys() {
TreeSet<String> result = new TreeSet<String>();
IBundleModel bundleModel = BundleModelFactory.getBundleModel(f.getProject());
if(bundleModel != null) {
IBundle bundle = bundleModel.getBundle(basename);
if(bundle != null) {
result.addAll(bundle.getPropertyNames());
}
}
return result;
}
}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.ca.AbstractELCompletionEngine#getMemberInfoByVariable(org.jboss.tools.common.el.core.resolver.IVariable, boolean)
*/
@Override
protected MemberInfo getMemberInfoByVariable(IVariable var,
boolean onlyEqualNames, int offset) {
return null;
}
/*
* (non-Javadoc)
* @see org.jboss.tools.common.el.core.ca.AbstractELCompletionEngine#resolveVariables(org.eclipse.core.resources.IFile, org.jboss.tools.common.el.core.model.ELInvocationExpression, boolean, boolean)
*/
@Override
public List<IVariable> resolveVariables(IFile file,
ELInvocationExpression expr, boolean isFinal, boolean onlyEqualNames, int offset) {
return null;
}
@Override
protected boolean isStaticMethodsCollectingEnabled() {
return false;
}
public IRelevanceCheck createRelevanceCheck(IJavaElement element) {
return new IRelevanceCheck() {
public boolean isRelevant(String content) {
return false;
}
};
}
IResourceBundle[] findResourceBundles (IBundleModel model) {
Map<String, IResourceBundle> result = new HashMap<String, IResourceBundle>();
for (String basename : model.getAllAvailableBundles()) {
String var = "bundles." + basename;
IResourceBundle resourceBundle = new ResourceBundle(basename, var);
result.put(var, resourceBundle);
}
return result.values().toArray(new IResourceBundle[0]);
}
}
| true | true | public ELResolutionImpl resolveELOperand(IFile file,
ELExpression operand, boolean returnEqualedVariablesOnly, IResourceBundle[] bundles)
throws BadLocationException, StringIndexOutOfBoundsException {
if(!(operand instanceof ELInvocationExpression) || file == null) {
return null;
}
ELInvocationExpression expr = (ELInvocationExpression)operand;
boolean isIncomplete = expr.getType() == ELObjectType.EL_PROPERTY_INVOCATION
&& ((ELPropertyInvocation)expr).getName() == null;
boolean isArgument = expr.getType() == ELObjectType.EL_ARGUMENT_INVOCATION;
ELResolutionImpl resolution = new ELResolutionImpl(expr);
ELInvocationExpression left = expr;
List<Variable> resolvedVariables = new ArrayList<Variable>();
if (expr.getLeft() != null && isArgument) {
left = expr.getLeft();
resolvedVariables = resolveVariables(file, left, bundles, false,
true); // is Final and equal names are because of
// we have no more to resolve the parts of expression,
// but we have to resolve arguments of probably a message component
if (resolvedVariables != null && !resolvedVariables.isEmpty()) {
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVariables) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
}
} else if (expr.getLeft() == null && isIncomplete) {
resolvedVariables = resolveVariables(file, expr, bundles, true,
returnEqualedVariablesOnly);
} else {
while(left != null) {
List<Variable>resolvedVars = new ArrayList<Variable>();
resolvedVars = resolveVariables(file,
left, bundles, left == expr,
returnEqualedVariablesOnly);
if (resolvedVars != null && !resolvedVars.isEmpty()) {
resolvedVariables = resolvedVars;
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVars) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
break;
}
left = (ELInvocationExpression)left.getLeft();
}
}
if (resolution.getLastResolvedToken() == null &&
!returnEqualedVariablesOnly &&
expr != null &&
isIncomplete) {
// no vars are resolved
// the tokens are the part of var name ended with a separator (.)
resolvedVariables = resolveVariables(file, expr, bundles, true, returnEqualedVariablesOnly);
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
if (left != null) {
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(false);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(varName.startsWith(operand.getText())) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
setImage(proposal);
proposals.add(proposal);
}
}
resolution.setProposals(proposals);
segment.setResolved(!proposals.isEmpty());
}
return resolution;
}
// Here we have a list of vars for some part of expression
// OK. we'll proceed with members of these vars
if (resolution.getLastResolvedToken() == operand) {
// First segment is the last one
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
ELSegmentImpl segment = new ELSegmentImpl(operand.getFirstToken());
segment.setResolved(true);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(operand.getLength()<=varName.length()) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
} else if(returnEqualedVariablesOnly) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName);
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
}
segment.getVariables().add(var);
}
resolution.setLastResolvedToken(expr);
resolution.setProposals(proposals);
return resolution;
}
//process segments one by one
if(left != null) {
while(left != expr) {
left = (ELInvocationExpression)left.getParent();
if (left != expr) { // inside expression
ELSegmentImpl segment = new ELSegmentImpl(left.getLastToken());
segment.setResolved(true);
resolution.addSegment(segment);
resolution.setLastResolvedToken(left);
return resolution;
} else { // Last segment
resolveLastSegment((ELInvocationExpression)operand, resolvedVariables, resolution, returnEqualedVariablesOnly);
break;
}
}
} else {
ELSegmentImpl segment = new ELSegmentImpl(expr.getFirstToken());
resolution.addSegment(segment);
}
return resolution;
}
| public ELResolutionImpl resolveELOperand(IFile file,
ELExpression operand, boolean returnEqualedVariablesOnly, IResourceBundle[] bundles)
throws BadLocationException, StringIndexOutOfBoundsException {
if(!(operand instanceof ELInvocationExpression) || file == null) {
return null;
}
ELInvocationExpression expr = (ELInvocationExpression)operand;
boolean isIncomplete = expr.getType() == ELObjectType.EL_PROPERTY_INVOCATION
&& ((ELPropertyInvocation)expr).getName() == null;
boolean isArgument = expr.getType() == ELObjectType.EL_ARGUMENT_INVOCATION;
ELResolutionImpl resolution = new ELResolutionImpl(expr);
ELInvocationExpression left = expr;
List<Variable> resolvedVariables = new ArrayList<Variable>();
if (expr.getLeft() != null && isArgument) {
left = expr.getLeft();
resolvedVariables = resolveVariables(file, left, bundles, false,
true); // is Final and equal names are because of
// we have no more to resolve the parts of expression,
// but we have to resolve arguments of probably a message component
if (resolvedVariables != null && !resolvedVariables.isEmpty()) {
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVariables) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
}
} else if (expr.getLeft() == null && isIncomplete) {
resolvedVariables = resolveVariables(file, expr, bundles, true,
returnEqualedVariablesOnly);
} else {
while(left != null) {
List<Variable>resolvedVars = new ArrayList<Variable>();
resolvedVars = resolveVariables(file,
left, bundles, left == expr,
returnEqualedVariablesOnly);
if (resolvedVars != null && !resolvedVars.isEmpty()) {
resolvedVariables = resolvedVars;
resolution.setLastResolvedToken(left);
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVars) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
if(left.getLastToken() != left.getFirstToken()) {
LexicalToken combined = left.getFirstToken().getNextToken().getCombinedToken(left.getLastToken());
segment = new MessagePropertyELSegmentImpl(combined);
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(true);
for (Variable variable : resolvedVars) {
segment.getVariables().add(variable);
}
resolution.addSegment(segment);
}
break;
}
left = (ELInvocationExpression)left.getLeft();
}
}
if (resolution.getLastResolvedToken() == null &&
!returnEqualedVariablesOnly &&
expr != null &&
isIncomplete) {
// no vars are resolved
// the tokens are the part of var name ended with a separator (.)
resolvedVariables = resolveVariables(file, expr, bundles, true, returnEqualedVariablesOnly);
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
if (left != null) {
ELSegmentImpl segment = new MessagePropertyELSegmentImpl(left.getFirstToken());
processMessageBundleSegment(expr, (MessagePropertyELSegmentImpl)segment, resolvedVariables);
segment.setResolved(false);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(varName.startsWith(operand.getText())) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
setImage(proposal);
proposals.add(proposal);
}
}
resolution.setProposals(proposals);
segment.setResolved(!proposals.isEmpty());
}
return resolution;
}
// Here we have a list of vars for some part of expression
// OK. we'll proceed with members of these vars
if (resolution.getLastResolvedToken() == operand) {
// First segment is the last one
Set<TextProposal> proposals = new TreeSet<TextProposal>(TextProposal.KB_PROPOSAL_ORDER);
ELSegmentImpl segment = new ELSegmentImpl(operand.getFirstToken());
segment.setResolved(true);
resolution.addSegment(segment);
for (Variable var : resolvedVariables) {
String varName = var.getName();
if(operand.getLength()<=varName.length()) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName.substring(operand.getLength()));
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
} else if(returnEqualedVariablesOnly) {
TextProposal proposal = new TextProposal();
proposal.setReplacementString(varName);
proposal.setLabel(varName);
setImage(proposal);
proposals.add(proposal);
}
segment.getVariables().add(var);
}
resolution.setLastResolvedToken(expr);
resolution.setProposals(proposals);
return resolution;
}
//process segments one by one
if(left != null) {
while(left != expr) {
left = (ELInvocationExpression)left.getParent();
if (left != expr) { // inside expression
ELSegmentImpl segment = new ELSegmentImpl(left.getLastToken());
segment.setResolved(true);
resolution.addSegment(segment);
resolution.setLastResolvedToken(left);
return resolution;
} else { // Last segment
resolveLastSegment((ELInvocationExpression)operand, resolvedVariables, resolution, returnEqualedVariablesOnly);
break;
}
}
} else {
ELSegmentImpl segment = new ELSegmentImpl(expr.getFirstToken());
resolution.addSegment(segment);
}
return resolution;
}
|
diff --git a/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfContentGenerator.java b/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfContentGenerator.java
index 5f81c4ca..cb860fd9 100755
--- a/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfContentGenerator.java
+++ b/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfContentGenerator.java
@@ -1,1047 +1,1047 @@
package org.pentaho.cdf;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.json.JSONException;
import org.json.JSONObject;
import org.pentaho.cdf.comments.CommentsEngine;
import org.pentaho.cdf.export.Export;
import org.pentaho.cdf.export.ExportCSV;
import org.pentaho.cdf.export.ExportExcel;
import org.pentaho.cdf.localization.MessageBundlesHelper;
import org.pentaho.cdf.storage.StorageEngine;
import org.pentaho.platform.api.engine.IActionSequenceResource;
import org.pentaho.platform.api.engine.ILogger;
import org.pentaho.platform.api.engine.IMimeTypeListener;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.IPluginResourceLoader;
import org.pentaho.platform.api.engine.IUITemplater;
import org.pentaho.platform.api.repository.IContentItem;
import org.pentaho.platform.api.repository.ISolutionRepository;
import org.pentaho.platform.engine.core.solution.ActionInfo;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.services.actionsequence.ActionResource;
import org.pentaho.platform.engine.services.solution.BaseContentGenerator;
import org.pentaho.platform.util.messages.LocaleHelper;
import org.pentaho.platform.util.web.MimeHelper;
import org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper;
import pt.webdetails.cpf.audit.CpfAuditHelper;
import pt.webdetails.packager.Packager;
/**
* This is the main class of the CDF plugin. It handles all requests to
* /pentaho/content/pentaho-cdf. These requests include:
* <p/>
* - JSONSolution
* - GetCDFResource
* - .xcdf requests
* - js files
* - files within resources
*
* @author Will Gorman ([email protected])
*/
public class CdfContentGenerator extends BaseContentGenerator {
private static final long serialVersionUID = 5608691656289862706L;
private static final Log logger = LogFactory.getLog(CdfContentGenerator.class);
public static final String PLUGIN_NAME = "pentaho-cdf"; //$NON-NLS-1$
private static final String MIMETYPE = "text/html"; //$NON-NLS-1$
public static final String SOLUTION_DIR = "cdf";
// Possible actions
private static final String RENDER_HTML = "/RenderHTML";
private static final String RENDER_XCDF = "/RenderXCDF";
private static final String JSON_SOLUTION = "/JSONSolution"; //$NON-NLS-1$
private static final String GET_CDF_RESOURCE = "/GetCDFResource"; //$NON-NLS-1$
private static final String EXPORT = "/Export"; //$NON-NLS-1$
private static final String SETTINGS = "/Settings"; //$NON-NLS-1$
private static final String CALLACTION = "/CallAction"; //$NON-NLS-1$
private static final String CLEAR_CACHE = "/ClearCache"; //$NON-NLS-1$
private static final String COMMENTS = "/Comments"; //$NON-NLS-1$
private static final String STORAGE = "/Storage"; //$NON-NLS-1$
private static final String GETHEADERS = "/GetHeaders"; //$NON-NLS-1$
private static final String CONTEXT = "/Context"; //$NON-NLS-1$
private static final String MIME_HTML = "text/html";
private static final String MIME_CSS = "text/css";
private static final String MIME_JS = "text/javascript";
private static final String MIME_PLAIN = "text/plain";
private static final String MIME_CSV = "text/csv";
private static final String MIME_XLS = "application/vnd.ms-excel";
// CDF Resource Relative URL
private static final String RELATIVE_URL_TAG = "@RELATIVE_URL@";
public String RELATIVE_URL;
private Packager packager;
public static String ENCODING = "UTF-8";
public CdfContentGenerator() {
try {
this.init();
} catch (Exception e) {
logger.error("Failed to initialize CDF");
}
}
@Override
public void createContent() throws Exception {
final OutputStream out;
final IContentItem contentItem;
final IParameterProvider pathParams;
final String method;
final String payload;
logger.info("[Timing] CDF content generator took over: " + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
try {
if (parameterProviders.get("path") != null
&& parameterProviders.get("path").getParameter("httprequest") != null
&& ((HttpServletRequest) parameterProviders.get("path").getParameter("httprequest")).getContextPath() != null) {
RELATIVE_URL = ((HttpServletRequest) parameterProviders.get("path").getParameter("httprequest")).getContextPath();
} else {
RELATIVE_URL = getBaseUrl();
/* If we detect an empty string, things will break.
* If we detect an absolute url, things will *probably* break.
* In either of these cases, we'll resort to Catalina's context,
* and its getContextPath() method for better results.
*/
if ("".equals(RELATIVE_URL) || RELATIVE_URL.matches("^http://.*")) {
Object context = PentahoSystem.getApplicationContext().getContext();
Method getContextPath = context.getClass().getMethod("getContextPath", null);
if (getContextPath != null) {
RELATIVE_URL = getContextPath.invoke(context, null).toString();
}
}
}
if (RELATIVE_URL.endsWith("/")) {
RELATIVE_URL = RELATIVE_URL.substring(0, RELATIVE_URL.length() - 1);
}
// If callbacks is properly setup, we assume we're being called from another plugin
if (this.callbacks != null && callbacks.size() > 0 && HashMap.class.isInstance(callbacks.get(0))) {
HashMap<String, Object> iface = (HashMap<String, Object>) callbacks.get(0);
pathParams = parameterProviders.get("path");
contentItem = outputHandler.getOutputContentItem("response", "content", "", instanceId, MIME_HTML);
out = (OutputStream) iface.get("output");
method = "/" + (String) iface.get("method");
payload = (String) iface.get("payload");
this.userSession = this.userSession != null ? this.userSession : (IPentahoSession) iface.get("usersession");
} else { // if not, we handle the request normally
pathParams = parameterProviders.get("path");
contentItem = outputHandler.getOutputContentItem("response", "content", "", instanceId, MIME_HTML);
out = contentItem.getOutputStream(null);
method = pathParams.getStringParameter("path", null);
payload = "";
}
// make sure we have a workable state
if (outputHandler == null) {
error(Messages.getErrorString("CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER")); //$NON-NLS-1$
throw new InvalidParameterException(Messages.getString("CdfContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER")); //$NON-NLS-1$
} else if (contentItem == null) {
error(Messages.getErrorString("CdfContentGenerator.ERROR_0002_NO_CONTENT_ITEM")); //$NON-NLS-1$
throw new InvalidParameterException(Messages.getString("CdfContentGenerator.ERROR_0002_NO_CONTENT_ITEM")); //$NON-NLS-1$
} else if (out == null) {
error(Messages.getErrorString("CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM")); //$NON-NLS-1$
throw new InvalidParameterException(Messages.getString("CdfContentGenerator.ERROR_0003_NO_OUTPUT_STREAM")); //$NON-NLS-1$
}
findMethod(method, contentItem, out, payload);
} catch (Exception e) {
logger.error("Error creating cdf content: ", e);
}
}
private void findMethod(final String urlPath, final IContentItem contentItem, final OutputStream out, String payload) throws Exception {
// Each block will call a different method. If in the future this extends a lot we can think
// about using reflection for class loading, but I don't expect that to happen.
final IParameterProvider requestParams = parameterProviders.get(IParameterProvider.SCOPE_REQUEST);
if (urlPath.equals(RENDER_XCDF)) {
renderXcdf(out, requestParams);
} else if (urlPath.equals(JSON_SOLUTION)) {
jsonSolution(out, requestParams);
} else if (urlPath.equals(GET_CDF_RESOURCE)) {
getCDFResource(urlPath, contentItem, out, requestParams);
} else if (urlPath.equals(RENDER_HTML)) {
renderHtml(out, requestParams);
} else if (urlPath.equals(EXPORT)) {
exportFile(requestParams, out);
} else if (urlPath.equals(SETTINGS)) {
cdfSettings(requestParams, out);
} else if (urlPath.equals(CALLACTION)) {
callAction(requestParams, out);
} else if (urlPath.equals(COMMENTS)) {
processComments(requestParams, out);
} else if (urlPath.equals(STORAGE)) {
processStorage(requestParams, out);
} else if (urlPath.equals(CONTEXT)) {
generateContext(requestParams, out);
} else if (urlPath.equals(CLEAR_CACHE)) {
clearCache(requestParams, out);
} else if (urlPath.equals(GETHEADERS)) {
if (!payload.equals("")) {
getHeaders(payload, requestParams, out);
} else {
getHeaders(requestParams, out);
}
} else {
// we'll be providing the actual content with cache
logger.warn("Getting resources through content generator is deprecated, please use static resources: " + urlPath);
returnResource(urlPath, contentItem, out);
}
}
private void generateContext(final IParameterProvider requestParams, final OutputStream out) throws Exception {
DashboardContext context = new DashboardContext(userSession);
out.write(context.getContext(requestParams).getBytes(ENCODING));
}
private void generateStorage(final IParameterProvider requestParams, final OutputStream out) throws Exception {
final StringBuilder s = new StringBuilder();
s.append("\n<script language=\"javascript\" type=\"text/javascript\">\n");
s.append(" Dashboards.storage = ");
s.append(StorageEngine.getInstance().read(requestParams, userSession)).append("\n");
s.append("</script>\n");
// setResponseHeaders(MIME_PLAIN,0,null);
out.write(s.toString().getBytes(ENCODING));
}
private void renderXcdf(final OutputStream out, final IParameterProvider requestParams) throws Exception {
long start = System.currentTimeMillis();
final String solution = requestParams.getStringParameter("solution", null); //$NON-NLS-1$
final String path = requestParams.getStringParameter("path", null); //$NON-NLS-1$
final String template = requestParams.getStringParameter("template", null); //$NON-NLS-1$
final String action = requestParams.getStringParameter("action", null); //$NON-NLS-1$
UUID uuid = CpfAuditHelper.startAudit(PLUGIN_NAME, requestParams.getParameter("action").toString(), getObjectName(), this.userSession, this, requestParams);
try {
final IMimeTypeListener mimeTypeListener = outputHandler.getMimeTypeListener();
if (mimeTypeListener != null) {
mimeTypeListener.setMimeType(MIMETYPE);
}
renderXCDFDashboard(requestParams, out, solution, path, action, template);
long end = System.currentTimeMillis();
CpfAuditHelper.endAudit(PLUGIN_NAME, requestParams.getParameter("action").toString(), getObjectName(), this.userSession, this, start, uuid, end);
} catch (Exception e) {
long end = System.currentTimeMillis();
CpfAuditHelper.endAudit(PLUGIN_NAME, requestParams.getParameter("action").toString(), getObjectName(), this.userSession, this, start, uuid, end);
throw e;
}
}
private void jsonSolution(final OutputStream out, final IParameterProvider requestParams) throws JSONException, ParserConfigurationException {
if (requestParams == null) {
error(Messages.getErrorString("CdfContentGenerator.ERROR_0004_NO_REQUEST_PARAMS")); //$NON-NLS-1$
throw new InvalidParameterException(Messages.getString("CdfContentGenerator.ERROR_0017_NO_REQUEST_PARAMS")); //$NON-NLS-1$
}
final String solution = requestParams.getStringParameter("solution", null); //$NON-NLS-1$
final String path = requestParams.getStringParameter("path", null); //$NON-NLS-1$
final String mode = requestParams.getStringParameter("mode", null); //$NON-NLS-1$
final String contextPath = ((HttpServletRequest) parameterProviders.get("path").getParameter("httprequest")).getContextPath();
final NavigateComponent nav = new NavigateComponent(userSession, contextPath);
final String json = nav.getNavigationElements(mode, solution, path);
final PrintWriter pw = new PrintWriter(out);
// jsonp?
String callback = requestParams.getStringParameter("callback", null);
if (callback != null) {
pw.println(callback + "(" + json + ");");
} else {
pw.println(json);
}
pw.flush();
}
private void getCDFResource(final String urlPath, final IContentItem contentItem, final OutputStream out, final IParameterProvider requestParams) throws Exception {
if (requestParams == null) {
error(Messages.getErrorString("CdfContentGenerator.ERROR_0004_NO_REQUEST_PARAMS")); //$NON-NLS-1$
throw new InvalidParameterException(Messages.getString("CdfContentGenerator.ERROR_0017_NO_REQUEST_PARAMS")); //$NON-NLS-1$
}
final String resource = requestParams.getStringParameter("resource", null); //$NON-NLS-1$
contentItem.setMimeType(MimeHelper.getMimeTypeFromFileName(resource));
//TODO: unused
// String[] allowedRoots = new String[2];
// allowedRoots[0] = PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME);
// allowedRoots[1] = PentahoSystem.getApplicationContext().getSolutionPath(SOLUTION_DIR);
final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse");
try {
getSolutionFile(resource, out, this);
} catch (SecurityException e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
private void renderHtml(final OutputStream out, final IParameterProvider requestParams) throws Exception {
final IMimeTypeListener mimeTypeListener = outputHandler.getMimeTypeListener();
if (mimeTypeListener != null) {
mimeTypeListener.setMimeType(MIMETYPE);
}
final String solution = requestParams.getStringParameter("solution", null); //$NON-NLS-1$
final String template = requestParams.getStringParameter("template", null); //$NON-NLS-1$
final String path = requestParams.getStringParameter("path", null); //$NON-NLS-1$
final String templateName = requestParams.getStringParameter("dashboard", null);
// Get messages base filename from url if given otherwise defaults to Messages
String messageBaseFilename = requestParams.getStringParameter("messages", null);
renderHtmlDashboard(requestParams, out, solution, path, templateName == null ? "template.html" : templateName, template, messageBaseFilename);
}
private void returnResource(final String urlPath, final IContentItem contentItem, final OutputStream out) throws Exception {
final IParameterProvider pathParams = parameterProviders.get("path"); //$NON-NLS-1$
contentItem.setMimeType(MimeHelper.getMimeTypeFromFileName(urlPath));
final IPluginResourceLoader resLoader = PentahoSystem.get(IPluginResourceLoader.class, null);
final String maxAge = resLoader.getPluginSetting(CdfContentGenerator.class, "settings/max-age");
final HttpServletResponse response = (HttpServletResponse) pathParams.getParameter("httpresponse");
if (maxAge != null && response != null) {
response.setHeader("Cache-Control", "max-age=" + maxAge);
}
getContent(urlPath, out, this);
}
public void renderXCDFDashboard(final IParameterProvider requestParams, final OutputStream out,
final String solution,
final String path,
final String action,
String template) throws Exception {
final String fullPath = ActionInfo.buildSolutionPath(solution, path, action);
// Check for access permissions
final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
if (repository.getSolutionFile(fullPath, ISolutionRepository.ACTION_EXECUTE) == null) {
out.write("Access Denied".getBytes(ENCODING));
return;
}
String templateName = null;
String messagesBaseFilename = null;
if (repository.resourceExists(fullPath)) {
final ActionResource resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", fullPath);
final String dashboardMetadata = repository.getResourceAsString(resource, ISolutionRepository.ACTION_EXECUTE);
final Document doc = DocumentHelper.parseText(dashboardMetadata);
templateName = XmlDom4JHelper.getNodeText("/cdf/template", doc, "");
// Get message file base name if any
if (doc.selectSingleNode("/cdf/messages") != null) {
messagesBaseFilename = XmlDom4JHelper.getNodeText("/cdf/messages", doc);
}
// If a "style" tag exists, use that one
if (doc.selectSingleNode("/cdf/style") != null) {
template = XmlDom4JHelper.getNodeText("/cdf/style", doc);
}
}
renderHtmlDashboard(requestParams, out, solution, path, templateName, template, messagesBaseFilename);
}
public void renderHtmlDashboard(final IParameterProvider requestParams, final OutputStream out,
final String solution,
final String path,
final String templateName,
String template,
String dashboardsMessagesBaseFilename) throws Exception {
if (template == null || template.equals("")) {
template = "";
} else {
template = "-" + template;
}
final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
final ActionResource resource;
String fullTemplatePath = null;
if (templateName != null) {
if (templateName.startsWith("/") || templateName.startsWith("\\")) { //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath = templateName;
} else {
fullTemplatePath = ActionInfo.buildSolutionPath(solution, path, templateName);
}
}
if (fullTemplatePath != null && repository.resourceExists(fullTemplatePath)) {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath);
} else {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
"system/" + PLUGIN_NAME + "/default-dashboard-template.html"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Check for access permissions
if (repository.getSolutionFile(resource, ISolutionRepository.ACTION_EXECUTE) == null) {
out.write("Access Denied".getBytes(ENCODING));
return;
}
String intro = ""; //$NON-NLS-1$
String footer = ""; //$NON-NLS-1$
final String dashboardTemplate = "template-dashboard" + template + ".html"; //$NON-NLS-1$
final IUITemplater templater = PentahoSystem.get(IUITemplater.class, userSession);
ArrayList<String> i18nTagsList = new ArrayList<String>();
if (templater != null) {
String solutionPath = SOLUTION_DIR + "/templates/" + dashboardTemplate;
if (!repository.resourceExists(solutionPath)) {//then try in system
solutionPath = "system/" + PLUGIN_NAME + "/" + dashboardTemplate;
}
final ActionResource templateResource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", solutionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String templateContent = repository.getResourceAsString(templateResource, ISolutionRepository.ACTION_EXECUTE);
// Process i18n on dashboard outer template
templateContent = updateUserLanguageKey(templateContent);
templateContent = processi18nTags(templateContent, i18nTagsList);
// Process i18n on dashboard outer template - end
final String[] sections = templater.breakTemplateString(templateContent, "", userSession); //$NON-NLS-1$
if (sections != null && sections.length > 0) {
intro = sections[0];
}
if (sections != null && sections.length > 1) {
footer = sections[1];
}
} else {
intro = Messages.getErrorString("CdfContentGenerator.ERROR_0005_BAD_TEMPLATE_OBJECT");
}
final String dashboardContent;
// TESTING to localize the template
//dashboardContent = repository.getResourceAsString(resource);
InputStream is = repository.getResourceInputStream(resource, true, ISolutionRepository.ACTION_EXECUTE);
// Fixed ISSUE #CDF-113
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(LocaleHelper.getSystemEncoding())));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Process i18n for each line of the dashboard output
line = processi18nTags(line, i18nTagsList);
// Process i18n - end
sb.append(line).append("\n");
}
is.close();
dashboardContent = sb.toString();
String messageSetPath = null;
// Merge dashboard related message file with global message file and save it in the dashboard cache
MessageBundlesHelper mbh = new MessageBundlesHelper(solution, path, dashboardsMessagesBaseFilename);
mbh.saveI18NMessageFilesToCache();
messageSetPath = mbh.getMessageFilesCacheUrl() + "/";
// If dashboard specific files aren't specified set message filename in cache to the global messages file filename
if (dashboardsMessagesBaseFilename == null) {
dashboardsMessagesBaseFilename = CdfConstants.BASE_GLOBAL_MESSAGE_SET_FILENAME;
}
intro = intro.replaceAll("\\{load\\}", "onload=\"load()\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
intro = intro.replaceAll("\\{body-tag-unload\\}", "");
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_NAME\\}", dashboardsMessagesBaseFilename);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_PATH\\}", messageSetPath);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET\\}", buildMessageSetCode(i18nTagsList));
/************************************************/
/* Add cdf libraries
/************************************************/
// final Date startDate = new Date();
final int headIndex = intro.indexOf("<head>");
final int length = intro.length();
// final Hashtable addedFiles = new Hashtable();
out.write(intro.substring(0, headIndex + 6).getBytes(ENCODING));
// Concat libraries to html head content
getHeaders(dashboardContent, requestParams, out);
- out.write(intro.substring(headIndex + 7, length - 1).getBytes(ENCODING));
+ out.write(intro.substring(headIndex + 6, length).getBytes(ENCODING));
// Add context
generateContext(requestParams, out);
// Add storage
generateStorage(requestParams, out);
out.write("<div id=\"dashboardContent\">".getBytes(ENCODING));
out.write(dashboardContent.getBytes(ENCODING));
out.write("</div>".getBytes(ENCODING));
out.write(footer.getBytes(ENCODING));
setResponseHeaders(MIME_HTML, 0, null);
}
private String buildMessageSetCode(ArrayList<String> tagsList) {
StringBuilder messageCodeSet = new StringBuilder();
for (String tag : tagsList) {
messageCodeSet.append("\\$('#").append(updateSelectorName(tag)).append("').html(jQuery.i18n.prop('").append(tag).append("'));\n");
}
return messageCodeSet.toString();
}
private String processi18nTags(String content, ArrayList<String> tagsList) {
String tagPattern = "CDF.i18n\\(\"";
String[] test = content.split(tagPattern);
if (test.length == 1) {
return content;
}
StringBuilder resBuffer = new StringBuilder();
int i;
String tagValue;
resBuffer.append(test[0]);
for (i = 1; i < test.length; i++) {
// First tag is processed differently that other because is the only case where I don't
// have key in first position
resBuffer.append("<span id=\"");
if (i != 0) {
// Right part of the string with the value of the tag herein
tagValue = test[i].substring(0, test[i].indexOf("\")"));
tagsList.add(tagValue);
resBuffer.append(updateSelectorName(tagValue));
resBuffer.append("\"></span>");
resBuffer.append(test[i].substring(test[i].indexOf("\")") + 2, test[i].length()));
}
}
return resBuffer.toString();
}
private String updateSelectorName(String name) {
// If we've the character . in the message key substitute it conventionally to _
// when dynamically generating the selector name. The "." character is not permitted in the
// selector id name
return name.replace(".", "_");
}
private String updateUserLanguageKey(String intro) {
// Fill the template with the correct user locale
Locale locale = LocaleHelper.getLocale();
if (logger.isDebugEnabled()) {
logger.debug("Current Pentaho user locale: " + locale.getLanguage());
}
intro = intro.replaceAll("#\\{LANGUAGE_CODE\\}", locale.getLanguage());
return intro;
}
private void exportFile(final IParameterProvider requestParams, final OutputStream output) {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ServiceCallAction serviceCallAction = ServiceCallAction.getInstance();
if (serviceCallAction.execute(requestParams, userSession, out)) {
final String exportType = requestParams.getStringParameter("exportType", "excel");
Export export;
if (exportType.equals("csv")) {
export = new ExportCSV(output);
setResponseHeaders(MIME_CSV, 0, "export" + export.getExtension());
} else {
export = new ExportExcel(output);
setResponseHeaders(MIME_XLS, 0, "export" + export.getExtension());
}
export.exportFile(new JSONObject(out.toString()));
}
} catch (IOException e) {
logger.error("IOException exporting file", e);
} catch (JSONException e) {
logger.error("JSONException exporting file", e);
}
}
private void cdfSettings(final IParameterProvider requestParams, final OutputStream out) {
final String method = requestParams.getStringParameter("method", null);
final String key = requestParams.getStringParameter("key", null);
if (method.equals("set")) {
CdfSettings.getInstance().setValue(key, requestParams.getParameter("value"), userSession);
} else {
final Object value = CdfSettings.getInstance().getValue(key, userSession);
final PrintWriter pw = new PrintWriter(out);
pw.println(value != null ? value.toString() : "");
pw.flush();
}
}
private void callAction(final IParameterProvider requestParams, final OutputStream out) {
final ServiceCallAction serviceCallAction = ServiceCallAction.getInstance();
serviceCallAction.execute(requestParams, userSession, out);
}
private void processComments(final IParameterProvider requestParams, final OutputStream out) throws JSONException {
String result;
try {
final CommentsEngine commentsEngine = CommentsEngine.getInstance();
result = commentsEngine.process(requestParams, userSession);
} catch (InvalidCdfOperationException ex) {
final String errMessage = ex.getCause().getClass().getName() + " - " + ex.getMessage();
logger.error("Error processing comment: " + errMessage);
final JSONObject json = new JSONObject();
json.put("error", errMessage);
result = json.toString(2);
}
final PrintWriter pw = new PrintWriter(out);
pw.println(result);
pw.flush();
}
private void processStorage(final IParameterProvider requestParams, final OutputStream out) throws JSONException {
String result;
try {
final StorageEngine storagesEngine = StorageEngine.getInstance();
result = storagesEngine.process(requestParams, userSession);
} catch (InvalidCdfOperationException ex) {
final String errMessage = ex.getCause().getClass().getName() + " - " + ex.getMessage();
logger.error("Error processing storage: " + errMessage);
final JSONObject json = new JSONObject();
json.put("error", errMessage);
result = json.toString(2);
}
final PrintWriter pw = new PrintWriter(out);
pw.println(result);
pw.flush();
}
@Override
public Log getLogger() {
// TODO Auto-generated method stub
return null;
}
public String concatFiles(String includeString, final Hashtable filesAdded, final Hashtable files) {
//TODO: is this used?
final String newLine = System.getProperty("line.separator");
final Enumeration keys = files.keys();
while (keys.hasMoreElements()) {
final String key = (String) keys.nextElement();
final String[] includeFiles = (String[]) files.get(key);
for (int i = 0; i < includeFiles.length; i++) {
if (!filesAdded.containsKey(includeFiles[i])) {
filesAdded.put(includeFiles[i], '1');
if (key.equals("script")) {
includeString += "<script language=\"javascript\" type=\"text/javascript\" src=\"" + includeFiles[i].replaceAll(RELATIVE_URL_TAG, RELATIVE_URL) + "\"></script>" + newLine;
} else {
includeString += "<link rel=\"stylesheet\" href=\"" + includeFiles[i].replaceAll(RELATIVE_URL_TAG, RELATIVE_URL) + "\" type=\"text/css\" />";
}
}
}
}
return includeString;
}
public boolean matchComponent(int keyIndex, final String key, final String content) {
for (int i = keyIndex - 1; i > 0; i--) {
if (content.charAt(i) == ':' || content.charAt(i) == '"' || ("" + content.charAt(i)).trim().equals("")) {
// noinspection UnnecessaryContinue
continue;
} else {
if ((i - 3) > 0 && content.substring((i - 3), i + 1).equals("type")) {
return true;
}
break;
}
}
keyIndex = content.indexOf(key, keyIndex + key.length());
if (keyIndex != -1) {
return matchComponent(keyIndex, key, content);
}
return false;
}
public void getContent(final String fileName, final OutputStream out, final ILogger logger) throws Exception {
// write out the scripts
// TODO support caching
final String path = PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME + fileName); //$NON-NLS-1$ //$NON-NLS-2$
final File file = new File(path);
final InputStream in = FileUtils.openInputStream(file);
try {
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
}
}
public void getSolutionFile(final String resourcePath, final OutputStream out, final ILogger logger) throws Exception {
final IPluginResourceLoader resLoader = PentahoSystem.get(IPluginResourceLoader.class, null);
final String formats = resLoader.getPluginSetting(this.getClass(), "settings/resources/downloadable-formats");
List<String> allowedFormats = Arrays.asList(StringUtils.split(formats, ','));
String extension = resourcePath.replaceAll(".*\\.(.*)", "$1");
if (allowedFormats.indexOf(extension) < 0) {
// We can't provide this type of file
throw new SecurityException("Not allowed");
}
final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
final InputStream in = repository.getResourceInputStream(resourcePath, true, ISolutionRepository.ACTION_EXECUTE);
try {
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
}
}
private void setResponseHeaders(final String mimeType, final int cacheDuration, final String attachmentName) {
// Make sure we have the correct mime type
final HttpServletResponse response = (HttpServletResponse) parameterProviders.get("path").getParameter("httpresponse");
response.setHeader("Content-Type", mimeType);
if (attachmentName != null) {
response.setHeader("content-disposition", "attachment; filename=" + attachmentName);
}
// Cache?
if (cacheDuration > 0) {
response.setHeader("Cache-Control", "max-age=" + cacheDuration);
} else {
response.setHeader("Cache-Control", "max-age=0, no-store");
}
}
private void getHeaders(final IParameterProvider requestParams, final OutputStream out) throws Exception {
String dashboard = requestParams.getStringParameter("dashboardContent", "");
getHeaders(dashboard, requestParams, out);
}
private void getHeaders(final String dashboardContent, final IParameterProvider requestParams, final OutputStream out) throws Exception {
final String dashboardType = requestParams.getStringParameter("dashboardType", "blueprint");
final String scheme = requestParams.hasParameter("scheme") ? requestParams.getStringParameter("scheme", "") : "http";
final String suffix;
final File file;
/*
* depending on the dashboard type, the minification engine and its file
* set will vary.
*/
logger.info("[Timing] opening resources file: " + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
if (dashboardType.equals("mobile")) {
suffix = "-mobile";
file = new File(PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME + "/resources-mobile.txt"));
} else if (dashboardType.equals("blueprint")) {
suffix = "";
file = new File(PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME + "/resources-blueprint.txt"));
} else {
suffix = "";
file = new File(PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME + "/resources-blueprint.txt"));
}
HashMap<String, String> includes = new HashMap<String, String>();
final Properties resources = new Properties();
resources.load(new FileInputStream(file));
final ArrayList<String> miniscripts = new ArrayList<String>();
final ArrayList<String> ministyles = new ArrayList<String>();
final ArrayList<String> scripts = new ArrayList<String>();
final ArrayList<String> styles = new ArrayList<String>();
miniscripts.addAll(Arrays.asList(resources.getProperty("commonLibrariesScript", "").split(",")));
ministyles.addAll(Arrays.asList(resources.getProperty("commonLibrariesLink", "").split(",")));
scripts.addAll(getExtraScripts(dashboardContent, resources));
styles.addAll(getExtraStyles(dashboardContent, resources));
styles.addAll(Arrays.asList(resources.getProperty("style", "").split(",")));
StringBuilder scriptsBuilders = new StringBuilder();
StringBuilder stylesBuilders = new StringBuilder();
final String absRoot = requestParams.hasParameter("root") ? (scheme.equals("") ? "" : (scheme + "://")) + requestParams.getParameter("root").toString() : "";
// Add common libraries
if (requestParams.hasParameter("debug") && requestParams.getParameter("debug").toString().equals("true")) {
// DEBUG MODE
for (String header : miniscripts) {
scriptsBuilders.append("<script type=\"text/javascript\" src=\"").append(header.replaceAll("@RELATIVE_URL@", absRoot + RELATIVE_URL)).append("\"></script>\n");
}
for (String header : ministyles) {
stylesBuilders.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(header.replaceAll("@RELATIVE_URL@", absRoot + RELATIVE_URL)).append( "\"/>\n");
}
} else {
// NORMAL MODE
logger.info("[Timing] starting minification: " + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
String stylesHash = packager.minifyPackage("styles" + suffix);
String scriptsHash = packager.minifyPackage("scripts" + suffix);
stylesBuilders.append("<link href=\"").append(absRoot).append(RELATIVE_URL).append("/content/pentaho-cdf/js/styles").append(suffix).append(".css?version=").append(stylesHash).append( "\" rel=\"stylesheet\" type=\"text/css\" />");
scriptsBuilders.append("<script type=\"text/javascript\" src=\"").append(absRoot).append( RELATIVE_URL).append("/content/pentaho-cdf/js/scripts" ).append(suffix).append(".js?version=").append(scriptsHash).append("\"></script>");
logger.info("[Timing] finished minification: " + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
}
// Add extra components libraries
for (String header : scripts) {
scriptsBuilders.append("<script type=\"text/javascript\" src=\"").append(header.replaceAll("@RELATIVE_URL@", absRoot + RELATIVE_URL)).append("\"></script>\n");
}
for (String header : styles) {
stylesBuilders.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(header.replaceAll("@RELATIVE_URL@", absRoot + RELATIVE_URL)).append("\"/>\n");
}
// Add ie8 blueprint condition
stylesBuilders.append("<!--[if lte IE 8]><link rel=\"stylesheet\" href=\"").append( absRoot).append(RELATIVE_URL)
.append("/content/pentaho-cdf/js/blueprint/ie.css\" type=\"text/css\" media=\"screen, projection\"><![endif]-->");
StringBuilder stuff = new StringBuilder();
includes.put("scripts", scriptsBuilders.toString());
includes.put("styles", stylesBuilders.toString());
for (String key : includes.keySet()) {
stuff.append(includes.get(key));
}
out.write(stuff.toString().getBytes("UTF8"));
}
private ArrayList<String> getExtraScripts(String dashboardContentOrig, Properties resources) {
// Compare this ignoring case
final String dashboardContent = dashboardContentOrig.toLowerCase();
ArrayList<String> scripts = new ArrayList<String>();
boolean all;
if (dashboardContent == null || StringUtils.isEmpty(dashboardContent)) {
all = true;
} else {
all = false;
}
final Enumeration<?> resourceKeys = resources.propertyNames();
while (resourceKeys.hasMoreElements()) {
final String scriptkey = (String) resourceKeys.nextElement();
final String key;
if (scriptkey.indexOf("Script") != -1 && scriptkey.indexOf("commonLibraries") == -1) {
key = scriptkey.replaceAll("Script$", "");
} else {
continue;
}
final int keyIndex = all ? 0 : dashboardContent.indexOf(key.toLowerCase());
if (keyIndex != -1) {
if (all || matchComponent(keyIndex, key.toLowerCase(), dashboardContent)) {
// ugly hack -- if we don't know for sure we need OpenStreetMaps,
// don't load it!
if (all && scriptkey.indexOf("mapScript") != -1) {
continue;
}
scripts.addAll(Arrays.asList(resources.getProperty(scriptkey).split(",")));
}
}
}
return scripts;
}
private ArrayList<String> getExtraStyles(String dashboardContentOrig, Properties resources) {
// Compare this ignoring case
final String dashboardContent = dashboardContentOrig.toLowerCase();
ArrayList<String> styles = new ArrayList<String>();
boolean all;
if (dashboardContent == null || StringUtils.isEmpty(dashboardContent)) {
all = true;
} else {
all = false;
}
if (dashboardContent != null && !StringUtils.isEmpty(dashboardContent)) {
final Enumeration<?> resourceKeys = resources.propertyNames();
while (resourceKeys.hasMoreElements()) {
final String scriptkey = (String) resourceKeys.nextElement();
final String key;
if (scriptkey.indexOf("Link") != -1 && scriptkey.indexOf("commonLibraries") == -1) {
key = scriptkey.replaceAll("Link$", "");
} else {
continue;
}
final int keyIndex = all ? 0 : dashboardContent.indexOf(key.toLowerCase());
if (keyIndex != -1) {
if (matchComponent(keyIndex, key.toLowerCase(), dashboardContent)) {
styles.addAll(Arrays.asList(resources.getProperty(scriptkey).split(",")));
}
}
}
}
return styles;
}
private void init() throws Exception {
String rootdir = PentahoSystem.getApplicationContext().getSolutionPath("system/" + PLUGIN_NAME);
final File blueprintFile = new File(rootdir + "/resources-blueprint.txt");
final File mobileFile = new File(rootdir + "/resources-mobile.txt");
final Properties blueprintResources = new Properties();
blueprintResources.load(new FileInputStream(blueprintFile));
final Properties mobileResources = new Properties();
mobileResources.load(new FileInputStream(mobileFile));
ArrayList<String> scriptsList = new ArrayList<String>();
ArrayList<String> stylesList = new ArrayList<String>();
this.packager = Packager.getInstance();
boolean scriptsAvailable = packager.isPackageRegistered("scripts");
boolean stylesAvailable = packager.isPackageRegistered("styles");
boolean mobileScriptsAvailable = packager.isPackageRegistered("scripts-mobile");
boolean mobileStylesAvailable = packager.isPackageRegistered("styles-mobile");
if (!scriptsAvailable) {
scriptsList.clear();
scriptsList.addAll(Arrays.asList(blueprintResources.get("commonLibrariesScript").toString().split(",")));
for (int i = 0; i < scriptsList.size(); i++) {
String fname = scriptsList.get(i);
scriptsList.set(i, fname.replaceAll(RELATIVE_URL_TAG + "/content/pentaho-cdf", ""));
}
packager.registerPackage("scripts", Packager.Filetype.JS, rootdir, rootdir + "/js/scripts.js", scriptsList.toArray(new String[scriptsList.size()]));
}
if (!stylesAvailable) {
stylesList.clear();
stylesList.addAll(Arrays.asList(blueprintResources.get("commonLibrariesLink").toString().split(",")));
for (int i = 0; i < stylesList.size(); i++) {
String fname = stylesList.get(i);
stylesList.set(i, fname.replaceAll(RELATIVE_URL_TAG + "/content/pentaho-cdf", ""));
}
packager.registerPackage("styles", Packager.Filetype.CSS, rootdir, rootdir + "/js/styles.css", stylesList.toArray(new String[stylesList.size()]));
}
if (!mobileScriptsAvailable) {
scriptsList.clear();
scriptsList.addAll(Arrays.asList(mobileResources.get("commonLibrariesScript").toString().split(",")));
for (int i = 0; i < scriptsList.size(); i++) {
String fname = scriptsList.get(i);
scriptsList.set(i, fname.replaceAll(RELATIVE_URL_TAG + "/content/pentaho-cdf", ""));
}
packager.registerPackage("scripts-mobile", Packager.Filetype.JS, rootdir, rootdir + "/js/scripts-mobile.js", scriptsList.toArray(new String[scriptsList.size()]));
}
if (!mobileStylesAvailable) {
stylesList.clear();
stylesList.addAll(Arrays.asList(mobileResources.get("commonLibrariesLink").toString().split(",")));
for (int i = 0; i < stylesList.size(); i++) {
String fname = stylesList.get(i);
stylesList.set(i, fname.replaceAll(RELATIVE_URL_TAG + "/content/pentaho-cdf", ""));
}
packager.registerPackage("styles-mobile", Packager.Filetype.CSS, rootdir, rootdir + "/js/styles-mobile.css", stylesList.toArray(new String[stylesList.size()]));
}
}
private static String getBaseUrl() {
String baseUrl;
try {
// Note - this method is deprecated and returns different values in 3.6
// and 3.7. Change this in future versions -- but not yet
// getFullyQualifiedServerUeRL only available from 3.7
// URI uri = new URI(PentahoSystem.getApplicationContext().getFullyQualifiedServerURL());
URI uri = new URI(PentahoSystem.getApplicationContext().getBaseUrl());
baseUrl = uri.getPath();
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
} catch (URISyntaxException ex) {
logger.fatal("Error building BaseURL from " + PentahoSystem.getApplicationContext().getBaseUrl(), ex);
baseUrl = "";
}
return baseUrl;
}
public void clearCache(final IParameterProvider requestParams, final OutputStream out) {
try {
DashboardContext.clearCache();
out.write("Cache cleared".getBytes("utf-8"));
} catch (IOException e) {
logger.error("failed to clear CDFcache");
}
}
}
| true | true | public void renderHtmlDashboard(final IParameterProvider requestParams, final OutputStream out,
final String solution,
final String path,
final String templateName,
String template,
String dashboardsMessagesBaseFilename) throws Exception {
if (template == null || template.equals("")) {
template = "";
} else {
template = "-" + template;
}
final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
final ActionResource resource;
String fullTemplatePath = null;
if (templateName != null) {
if (templateName.startsWith("/") || templateName.startsWith("\\")) { //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath = templateName;
} else {
fullTemplatePath = ActionInfo.buildSolutionPath(solution, path, templateName);
}
}
if (fullTemplatePath != null && repository.resourceExists(fullTemplatePath)) {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath);
} else {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
"system/" + PLUGIN_NAME + "/default-dashboard-template.html"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Check for access permissions
if (repository.getSolutionFile(resource, ISolutionRepository.ACTION_EXECUTE) == null) {
out.write("Access Denied".getBytes(ENCODING));
return;
}
String intro = ""; //$NON-NLS-1$
String footer = ""; //$NON-NLS-1$
final String dashboardTemplate = "template-dashboard" + template + ".html"; //$NON-NLS-1$
final IUITemplater templater = PentahoSystem.get(IUITemplater.class, userSession);
ArrayList<String> i18nTagsList = new ArrayList<String>();
if (templater != null) {
String solutionPath = SOLUTION_DIR + "/templates/" + dashboardTemplate;
if (!repository.resourceExists(solutionPath)) {//then try in system
solutionPath = "system/" + PLUGIN_NAME + "/" + dashboardTemplate;
}
final ActionResource templateResource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", solutionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String templateContent = repository.getResourceAsString(templateResource, ISolutionRepository.ACTION_EXECUTE);
// Process i18n on dashboard outer template
templateContent = updateUserLanguageKey(templateContent);
templateContent = processi18nTags(templateContent, i18nTagsList);
// Process i18n on dashboard outer template - end
final String[] sections = templater.breakTemplateString(templateContent, "", userSession); //$NON-NLS-1$
if (sections != null && sections.length > 0) {
intro = sections[0];
}
if (sections != null && sections.length > 1) {
footer = sections[1];
}
} else {
intro = Messages.getErrorString("CdfContentGenerator.ERROR_0005_BAD_TEMPLATE_OBJECT");
}
final String dashboardContent;
// TESTING to localize the template
//dashboardContent = repository.getResourceAsString(resource);
InputStream is = repository.getResourceInputStream(resource, true, ISolutionRepository.ACTION_EXECUTE);
// Fixed ISSUE #CDF-113
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(LocaleHelper.getSystemEncoding())));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Process i18n for each line of the dashboard output
line = processi18nTags(line, i18nTagsList);
// Process i18n - end
sb.append(line).append("\n");
}
is.close();
dashboardContent = sb.toString();
String messageSetPath = null;
// Merge dashboard related message file with global message file and save it in the dashboard cache
MessageBundlesHelper mbh = new MessageBundlesHelper(solution, path, dashboardsMessagesBaseFilename);
mbh.saveI18NMessageFilesToCache();
messageSetPath = mbh.getMessageFilesCacheUrl() + "/";
// If dashboard specific files aren't specified set message filename in cache to the global messages file filename
if (dashboardsMessagesBaseFilename == null) {
dashboardsMessagesBaseFilename = CdfConstants.BASE_GLOBAL_MESSAGE_SET_FILENAME;
}
intro = intro.replaceAll("\\{load\\}", "onload=\"load()\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
intro = intro.replaceAll("\\{body-tag-unload\\}", "");
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_NAME\\}", dashboardsMessagesBaseFilename);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_PATH\\}", messageSetPath);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET\\}", buildMessageSetCode(i18nTagsList));
/************************************************/
/* Add cdf libraries
/************************************************/
// final Date startDate = new Date();
final int headIndex = intro.indexOf("<head>");
final int length = intro.length();
// final Hashtable addedFiles = new Hashtable();
out.write(intro.substring(0, headIndex + 6).getBytes(ENCODING));
// Concat libraries to html head content
getHeaders(dashboardContent, requestParams, out);
out.write(intro.substring(headIndex + 7, length - 1).getBytes(ENCODING));
// Add context
generateContext(requestParams, out);
// Add storage
generateStorage(requestParams, out);
out.write("<div id=\"dashboardContent\">".getBytes(ENCODING));
out.write(dashboardContent.getBytes(ENCODING));
out.write("</div>".getBytes(ENCODING));
out.write(footer.getBytes(ENCODING));
setResponseHeaders(MIME_HTML, 0, null);
}
| public void renderHtmlDashboard(final IParameterProvider requestParams, final OutputStream out,
final String solution,
final String path,
final String templateName,
String template,
String dashboardsMessagesBaseFilename) throws Exception {
if (template == null || template.equals("")) {
template = "";
} else {
template = "-" + template;
}
final ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
final ActionResource resource;
String fullTemplatePath = null;
if (templateName != null) {
if (templateName.startsWith("/") || templateName.startsWith("\\")) { //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath = templateName;
} else {
fullTemplatePath = ActionInfo.buildSolutionPath(solution, path, templateName);
}
}
if (fullTemplatePath != null && repository.resourceExists(fullTemplatePath)) {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
fullTemplatePath);
} else {
resource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
"system/" + PLUGIN_NAME + "/default-dashboard-template.html"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Check for access permissions
if (repository.getSolutionFile(resource, ISolutionRepository.ACTION_EXECUTE) == null) {
out.write("Access Denied".getBytes(ENCODING));
return;
}
String intro = ""; //$NON-NLS-1$
String footer = ""; //$NON-NLS-1$
final String dashboardTemplate = "template-dashboard" + template + ".html"; //$NON-NLS-1$
final IUITemplater templater = PentahoSystem.get(IUITemplater.class, userSession);
ArrayList<String> i18nTagsList = new ArrayList<String>();
if (templater != null) {
String solutionPath = SOLUTION_DIR + "/templates/" + dashboardTemplate;
if (!repository.resourceExists(solutionPath)) {//then try in system
solutionPath = "system/" + PLUGIN_NAME + "/" + dashboardTemplate;
}
final ActionResource templateResource = new ActionResource("", IActionSequenceResource.SOLUTION_FILE_RESOURCE, "text/xml", solutionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String templateContent = repository.getResourceAsString(templateResource, ISolutionRepository.ACTION_EXECUTE);
// Process i18n on dashboard outer template
templateContent = updateUserLanguageKey(templateContent);
templateContent = processi18nTags(templateContent, i18nTagsList);
// Process i18n on dashboard outer template - end
final String[] sections = templater.breakTemplateString(templateContent, "", userSession); //$NON-NLS-1$
if (sections != null && sections.length > 0) {
intro = sections[0];
}
if (sections != null && sections.length > 1) {
footer = sections[1];
}
} else {
intro = Messages.getErrorString("CdfContentGenerator.ERROR_0005_BAD_TEMPLATE_OBJECT");
}
final String dashboardContent;
// TESTING to localize the template
//dashboardContent = repository.getResourceAsString(resource);
InputStream is = repository.getResourceInputStream(resource, true, ISolutionRepository.ACTION_EXECUTE);
// Fixed ISSUE #CDF-113
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(LocaleHelper.getSystemEncoding())));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Process i18n for each line of the dashboard output
line = processi18nTags(line, i18nTagsList);
// Process i18n - end
sb.append(line).append("\n");
}
is.close();
dashboardContent = sb.toString();
String messageSetPath = null;
// Merge dashboard related message file with global message file and save it in the dashboard cache
MessageBundlesHelper mbh = new MessageBundlesHelper(solution, path, dashboardsMessagesBaseFilename);
mbh.saveI18NMessageFilesToCache();
messageSetPath = mbh.getMessageFilesCacheUrl() + "/";
// If dashboard specific files aren't specified set message filename in cache to the global messages file filename
if (dashboardsMessagesBaseFilename == null) {
dashboardsMessagesBaseFilename = CdfConstants.BASE_GLOBAL_MESSAGE_SET_FILENAME;
}
intro = intro.replaceAll("\\{load\\}", "onload=\"load()\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
intro = intro.replaceAll("\\{body-tag-unload\\}", "");
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_NAME\\}", dashboardsMessagesBaseFilename);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET_PATH\\}", messageSetPath);
intro = intro.replaceAll("#\\{GLOBAL_MESSAGE_SET\\}", buildMessageSetCode(i18nTagsList));
/************************************************/
/* Add cdf libraries
/************************************************/
// final Date startDate = new Date();
final int headIndex = intro.indexOf("<head>");
final int length = intro.length();
// final Hashtable addedFiles = new Hashtable();
out.write(intro.substring(0, headIndex + 6).getBytes(ENCODING));
// Concat libraries to html head content
getHeaders(dashboardContent, requestParams, out);
out.write(intro.substring(headIndex + 6, length).getBytes(ENCODING));
// Add context
generateContext(requestParams, out);
// Add storage
generateStorage(requestParams, out);
out.write("<div id=\"dashboardContent\">".getBytes(ENCODING));
out.write(dashboardContent.getBytes(ENCODING));
out.write("</div>".getBytes(ENCODING));
out.write(footer.getBytes(ENCODING));
setResponseHeaders(MIME_HTML, 0, null);
}
|
diff --git a/src/main/java/hudson/plugins/javanet/PluginImpl.java b/src/main/java/hudson/plugins/javanet/PluginImpl.java
index 5f59013..e02d279 100644
--- a/src/main/java/hudson/plugins/javanet/PluginImpl.java
+++ b/src/main/java/hudson/plugins/javanet/PluginImpl.java
@@ -1,57 +1,57 @@
package hudson.plugins.javanet;
import hudson.Plugin;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Jobs;
import hudson.model.listeners.ItemListener;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.IOException;
/**
* @author Kohsuke Kawaguchi
*/
public class PluginImpl extends Plugin {
public void start() {
Jobs.PROPERTIES.add(StatsProperty.DESCRIPTOR);
Hudson.getInstance().getJobListeners().add(new ItemListener() {
public void onLoaded() {
// when we are installed for the first time, hook this up to all existing jobs
// so that this can be seen w/o reconfiguration.
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null)
try {
- j.addProperty(new StatsProperty());
+ ((AbstractProject)j).addProperty(new StatsProperty());
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to persist "+j,e);
}
}
Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() {
protected void doRun() {
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null) continue;
JavaNetStatsAction a = p.getJobAction(j);
if(a==null) continue;
a.upToDateCheck();
}
}
},10*MINUTE,3*HOUR);
}
});
}
static final long MINUTE = 1000*60;
static final long HOUR = 24*60*MINUTE;
static final long DAY = 24*HOUR;
private static final Logger LOGGER = Logger.getLogger(PluginImpl.class.getName());
}
| true | true | public void start() {
Jobs.PROPERTIES.add(StatsProperty.DESCRIPTOR);
Hudson.getInstance().getJobListeners().add(new ItemListener() {
public void onLoaded() {
// when we are installed for the first time, hook this up to all existing jobs
// so that this can be seen w/o reconfiguration.
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null)
try {
j.addProperty(new StatsProperty());
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to persist "+j,e);
}
}
Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() {
protected void doRun() {
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null) continue;
JavaNetStatsAction a = p.getJobAction(j);
if(a==null) continue;
a.upToDateCheck();
}
}
},10*MINUTE,3*HOUR);
}
});
}
| public void start() {
Jobs.PROPERTIES.add(StatsProperty.DESCRIPTOR);
Hudson.getInstance().getJobListeners().add(new ItemListener() {
public void onLoaded() {
// when we are installed for the first time, hook this up to all existing jobs
// so that this can be seen w/o reconfiguration.
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null)
try {
((AbstractProject)j).addProperty(new StatsProperty());
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to persist "+j,e);
}
}
Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() {
protected void doRun() {
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
StatsProperty p = j.getProperty(StatsProperty.class);
if(p==null) continue;
JavaNetStatsAction a = p.getJobAction(j);
if(a==null) continue;
a.upToDateCheck();
}
}
},10*MINUTE,3*HOUR);
}
});
}
|
diff --git a/src/com/ichi2/anki/Download.java b/src/com/ichi2/anki/Download.java
index e0d90bad..4010ca18 100644
--- a/src/com/ichi2/anki/Download.java
+++ b/src/com/ichi2/anki/Download.java
@@ -1,173 +1,173 @@
/***************************************************************************************
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.HashMap;
public class Download extends HashMap<String, Object> implements Parcelable {
// Status codes
public static final int STATUS_STARTED = -1;
public static final int STATUS_DOWNLOADING = 0;
public static final int STATUS_PAUSED = 1;
public static final int STATUS_COMPLETE = 2;
public static final int STATUS_CANCELLED = 3;
public static final int STATUS_ERROR = 4;
private static final long serialVersionUID = 1L;
// Download's title
private String mTitle;
// Download's filename
private String mFilename;
// Download URL
private String mUrl;
// Size of download in bytes
private long mSize;
// Number of bytes downloaded
private long mDownloaded;
// Current status of download
protected int mStatus;
public Download(String title) {
mTitle = title;
this.put(title, true);
mSize = -1;
mDownloaded = 0;
mStatus = STATUS_STARTED;
// The deck file name should match the deck title. The only characters that we cannot
// absolutely allow to appear in the filename are the ones reserved in some file system.
// Currently these include \, /, and :, in order to cover Linux, OSX, and Windows.
- mFilename = mTitle.replaceAll(":/\\", "");
+ mFilename = mTitle.replaceAll(":/\\\\", "");
if (mFilename.length() > 40) {
mFilename = mFilename.substring(0, 40);
}
}
public long getSize() {
return mSize;
}
public void setSize(long size) {
mSize = size;
}
public long getDownloaded() {
return mDownloaded;
}
public void setDownloaded(long downloaded) {
mDownloaded = downloaded;
}
public String getEstTimeToCompletion() {
return "";
}
public void setEstTimeToCompletion(double estTime) {
// pass
}
public int getProgress() {
return (int) (((float) mDownloaded / mSize) * 100);
}
public int getStatus() {
return mStatus;
}
public void setStatus(int status) {
mStatus = status;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
this.remove(mTitle);
this.put(title, true);
mTitle = title;
mFilename = title;
}
public String getFilename() {
return mFilename;
}
/********************************************************************
* Parcel methods *
********************************************************************/
public Download(Parcel in) {
readFromParcel(in);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mUrl);
dest.writeLong(mSize);
dest.writeLong(mDownloaded);
dest.writeInt(mStatus);
dest.writeString(mTitle);
}
protected void readFromParcel(Parcel in) {
mUrl = in.readString();
mSize = in.readLong();
mDownloaded = in.readLong();
mStatus = in.readInt();
mTitle = in.readString();
}
public static final Parcelable.Creator<Download> CREATOR = new Parcelable.Creator<Download>() {
@Override
public Download createFromParcel(Parcel in) {
return new Download(in);
}
@Override
public Download[] newArray(int size) {
return new Download[size];
}
};
}
| true | true | public Download(String title) {
mTitle = title;
this.put(title, true);
mSize = -1;
mDownloaded = 0;
mStatus = STATUS_STARTED;
// The deck file name should match the deck title. The only characters that we cannot
// absolutely allow to appear in the filename are the ones reserved in some file system.
// Currently these include \, /, and :, in order to cover Linux, OSX, and Windows.
mFilename = mTitle.replaceAll(":/\\", "");
if (mFilename.length() > 40) {
mFilename = mFilename.substring(0, 40);
}
}
| public Download(String title) {
mTitle = title;
this.put(title, true);
mSize = -1;
mDownloaded = 0;
mStatus = STATUS_STARTED;
// The deck file name should match the deck title. The only characters that we cannot
// absolutely allow to appear in the filename are the ones reserved in some file system.
// Currently these include \, /, and :, in order to cover Linux, OSX, and Windows.
mFilename = mTitle.replaceAll(":/\\\\", "");
if (mFilename.length() > 40) {
mFilename = mFilename.substring(0, 40);
}
}
|
diff --git a/src/main/java/org/gatein/security/oauth/portlet/facebook/FacebookStatusUpdatePortlet.java b/src/main/java/org/gatein/security/oauth/portlet/facebook/FacebookStatusUpdatePortlet.java
index 8f1b86a..97f9535 100644
--- a/src/main/java/org/gatein/security/oauth/portlet/facebook/FacebookStatusUpdatePortlet.java
+++ b/src/main/java/org/gatein/security/oauth/portlet/facebook/FacebookStatusUpdatePortlet.java
@@ -1,229 +1,229 @@
/*
* JBoss, a division of Red Hat
* Copyright 2013, Red Hat Middleware, LLC, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.security.oauth.portlet.facebook;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletSession;
import javax.portlet.PortletURL;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookOAuthException;
import com.restfb.types.FacebookType;
import org.exoplatform.container.ExoContainer;
import org.gatein.security.oauth.common.OAuthConstants;
import org.gatein.security.oauth.common.OAuthProviderType;
import org.gatein.security.oauth.facebook.FacebookAccessTokenContext;
import org.gatein.security.oauth.portlet.AbstractSocialPortlet;
/**
* @author <a href="mailto:[email protected]">Marek Posolda</a>
*/
public class FacebookStatusUpdatePortlet extends AbstractSocialPortlet<FacebookAccessTokenContext> {
private static final String ACTION_UPDATE_STATUS = "_updateStatus";
private static final String ACTION_BACK = "_backToForm";
private static final String ATTR_FB_ACCESS_TOKEN = "AttributeFacebookAccessToken";
private static final String RENDER_PARAM_STATUS = "renderParamStatus";
private static final String RENDER_PARAM_ERROR_MESSAGE = "renderParamErrorMessage";
private enum Status {
SUCCESS,
NOT_SPECIFIED_MESSAGE_OR_LINK,
FACEBOOK_ERROR_INSUFFICIENT_SCOPE,
FACEBOOK_ERROR_OTHER
}
@Override
protected void afterInit(ExoContainer container) {
}
@Override
protected OAuthProviderType<FacebookAccessTokenContext> getOAuthProvider() {
return getOauthProviderTypeRegistry().getOAuthProvider(OAuthConstants.OAUTH_PROVIDER_KEY_FACEBOOK);
}
@Override
protected void handleRender(RenderRequest request, RenderResponse response, FacebookAccessTokenContext accessToken) throws IOException {
PrintWriter out = response.getWriter();
PortletSession session = request.getPortletSession();
// Process status
String statusParam = request.getParameter(RENDER_PARAM_STATUS);
if (statusParam != null) {
Status status = Status.valueOf(statusParam);
if (status == Status.SUCCESS) {
out.println("Your message has been successfully published on your Facebook wall!<br>");
- } else if (status == Status.SUCCESS) {
+ } else if (status == Status.NOT_SPECIFIED_MESSAGE_OR_LINK) {
out.println("Either message or link needs to be specified!<br>");
} else if (status == Status.FACEBOOK_ERROR_INSUFFICIENT_SCOPE) {
String neededScope = "publish_stream";
out.println("You have insufficient privileges (Facebook scope) to publish message on your FB wall. Your access token need to have scope: <b>" + neededScope + "</b><br>");
// Create URL for start OAuth2 flow with custom scope added
PortletURL actionURL = response.createActionURL();
actionURL.setParameter(ActionRequest.ACTION_NAME, AbstractSocialPortlet.ACTION_OAUTH_REDIRECT);
actionURL.setParameter(OAuthConstants.PARAM_CUSTOM_SCOPE, neededScope);
out.println("Click <a style=\"color: blue;\" href=\"" + actionURL + "\">here</a> to fix it<br>");
} else if (status == Status.FACEBOOK_ERROR_OTHER) {
String errorMessage = request.getParameter(RENDER_PARAM_ERROR_MESSAGE);
out.println("Error occured during facebook processing. Error details: " + errorMessage + "<br>");
}
PortletURL backURL = response.createActionURL();
backURL.setParameter(ActionRequest.ACTION_NAME, ACTION_BACK);
out.println("<a style=\"color: blue;\" href=\"" + backURL + "\">Back</a><br>");
return;
}
PortletURL url = response.createActionURL();
url.setParameter(ActionRequest.ACTION_NAME, ACTION_UPDATE_STATUS);
// TODO: jsp?
out.println("<h3>Publish some content to your facebook wall</h3>");
out.println("<div style=\"font-size: 13px;\">Either message or link are required fields</div><br>");
out.println("<form method=\"POST\" action=\"" + url + "\">");
out.println("<table>");
out.println(renderInput("message", true, session));
out.println("<tr><td></td><td></td></tr>");
out.println("<tr><td colspan=2><div style=\"font-size: 13px;\">Other parameters, which are important only if you want to publish some link</div></td></tr>");
out.println(renderInput("link", true, session));
out.println(renderInput("picture", false, session));
out.println(renderInput("name", false, session));
out.println(renderInput("caption", false, session));
out.println(renderInput("description", false, session));
out.println("</table>");
out.println("<input type=\"submit\" value=\"submit\" />");
out.println("</form>");
// Save FB AccessToken to session, so it could be used in actionUpdateStatus
request.getPortletSession().setAttribute(ATTR_FB_ACCESS_TOKEN, accessToken);
}
@ProcessAction(name = ACTION_UPDATE_STATUS)
public void actionUpdateStatus(ActionRequest aReq, ActionResponse aResp) throws IOException {
PortletSession session = aReq.getPortletSession();
String message = getParameterAndSaveItToSession("message", aReq, session);
String link = getParameterAndSaveItToSession("link", aReq, session);
String picture = getParameterAndSaveItToSession("picture", aReq, session);
String name = getParameterAndSaveItToSession("name", aReq, session);
String caption = getParameterAndSaveItToSession("caption", aReq, session);
String description = getParameterAndSaveItToSession("description", aReq, session);
if (isEmpty(message) && isEmpty(link)) {
aResp.setRenderParameter(RENDER_PARAM_STATUS, Status.NOT_SPECIFIED_MESSAGE_OR_LINK.name());
return;
}
if (log.isTraceEnabled()) {
StringBuilder builder = new StringBuilder("message=" + message)
.append(", link=" + link)
.append(", picture=" + picture)
.append(", name=" + name)
.append(", caption=" + caption)
.append(", description=" + description);
log.trace(builder.toString());
}
// Obtain accessToken from portlet session
FacebookAccessTokenContext accessTokenContext = (FacebookAccessTokenContext)aReq.getPortletSession().getAttribute(ATTR_FB_ACCESS_TOKEN);
FacebookClient facebookClient = new DefaultFacebookClient(accessTokenContext.getAccessToken());
List<Parameter> params = new ArrayList<Parameter>();
appendParam(params, "message", message);
appendParam(params, "link", link);
appendParam(params, "picture", picture);
appendParam(params, "name", name);
appendParam(params, "caption", caption);
appendParam(params, "description", description);
try {
FacebookType publishMessageResponse = facebookClient.publish("me/feed", FacebookType.class, params.toArray(new Parameter[] {}));
if (publishMessageResponse.getId() != null) {
log.debug("Message published successfully to Facebook profile of user " + aReq.getRemoteUser() + " with ID " + publishMessageResponse.getId());
aResp.setRenderParameter(RENDER_PARAM_STATUS, Status.SUCCESS.name());
}
} catch (FacebookOAuthException foe) {
String exMessage = foe.getErrorCode() + " - " + foe.getErrorType() + " - " + foe.getErrorMessage();
log.warn(exMessage);
if (foe.getErrorMessage().contains("The user hasn't authorized the application to perform this action")) {
aResp.setRenderParameter(RENDER_PARAM_STATUS, Status.FACEBOOK_ERROR_INSUFFICIENT_SCOPE.name());
} else {
aResp.setRenderParameter(RENDER_PARAM_STATUS, Status.FACEBOOK_ERROR_OTHER.name());
aResp.setRenderParameter(RENDER_PARAM_ERROR_MESSAGE, exMessage);
}
}
}
@ProcessAction(name = ACTION_BACK)
public void actionBack(ActionRequest aReq, ActionResponse aResp) throws IOException {
aResp.removePublicRenderParameter(RENDER_PARAM_STATUS);
aResp.removePublicRenderParameter(RENDER_PARAM_ERROR_MESSAGE);
}
private String renderInput(String inputName, boolean required, PortletSession session) {
String label = inputName.substring(0, 1).toUpperCase() + inputName.substring(1);
StringBuilder result = new StringBuilder("<tr><td>" + label + ": </td><td><input name=\"").
append(inputName + "\"");
// Try to read value from session
String value = (String)session.getAttribute(inputName);
if (value != null) {
result.append(" value=\"" + value + "\"");
}
result.append(" />");
if (required) {
result = result.append(" *");
}
return result.append("</td></tr>").toString();
}
private boolean isEmpty(String message) {
return message == null || message.length() == 0;
}
private void appendParam(List<Parameter> params, String paramName, String paramValue) {
if (paramValue != null) {
params.add(Parameter.with(paramName, paramValue));
}
}
}
| true | true | protected void handleRender(RenderRequest request, RenderResponse response, FacebookAccessTokenContext accessToken) throws IOException {
PrintWriter out = response.getWriter();
PortletSession session = request.getPortletSession();
// Process status
String statusParam = request.getParameter(RENDER_PARAM_STATUS);
if (statusParam != null) {
Status status = Status.valueOf(statusParam);
if (status == Status.SUCCESS) {
out.println("Your message has been successfully published on your Facebook wall!<br>");
} else if (status == Status.SUCCESS) {
out.println("Either message or link needs to be specified!<br>");
} else if (status == Status.FACEBOOK_ERROR_INSUFFICIENT_SCOPE) {
String neededScope = "publish_stream";
out.println("You have insufficient privileges (Facebook scope) to publish message on your FB wall. Your access token need to have scope: <b>" + neededScope + "</b><br>");
// Create URL for start OAuth2 flow with custom scope added
PortletURL actionURL = response.createActionURL();
actionURL.setParameter(ActionRequest.ACTION_NAME, AbstractSocialPortlet.ACTION_OAUTH_REDIRECT);
actionURL.setParameter(OAuthConstants.PARAM_CUSTOM_SCOPE, neededScope);
out.println("Click <a style=\"color: blue;\" href=\"" + actionURL + "\">here</a> to fix it<br>");
} else if (status == Status.FACEBOOK_ERROR_OTHER) {
String errorMessage = request.getParameter(RENDER_PARAM_ERROR_MESSAGE);
out.println("Error occured during facebook processing. Error details: " + errorMessage + "<br>");
}
PortletURL backURL = response.createActionURL();
backURL.setParameter(ActionRequest.ACTION_NAME, ACTION_BACK);
out.println("<a style=\"color: blue;\" href=\"" + backURL + "\">Back</a><br>");
return;
}
PortletURL url = response.createActionURL();
url.setParameter(ActionRequest.ACTION_NAME, ACTION_UPDATE_STATUS);
// TODO: jsp?
out.println("<h3>Publish some content to your facebook wall</h3>");
out.println("<div style=\"font-size: 13px;\">Either message or link are required fields</div><br>");
out.println("<form method=\"POST\" action=\"" + url + "\">");
out.println("<table>");
out.println(renderInput("message", true, session));
out.println("<tr><td></td><td></td></tr>");
out.println("<tr><td colspan=2><div style=\"font-size: 13px;\">Other parameters, which are important only if you want to publish some link</div></td></tr>");
out.println(renderInput("link", true, session));
out.println(renderInput("picture", false, session));
out.println(renderInput("name", false, session));
out.println(renderInput("caption", false, session));
out.println(renderInput("description", false, session));
out.println("</table>");
out.println("<input type=\"submit\" value=\"submit\" />");
out.println("</form>");
// Save FB AccessToken to session, so it could be used in actionUpdateStatus
request.getPortletSession().setAttribute(ATTR_FB_ACCESS_TOKEN, accessToken);
}
| protected void handleRender(RenderRequest request, RenderResponse response, FacebookAccessTokenContext accessToken) throws IOException {
PrintWriter out = response.getWriter();
PortletSession session = request.getPortletSession();
// Process status
String statusParam = request.getParameter(RENDER_PARAM_STATUS);
if (statusParam != null) {
Status status = Status.valueOf(statusParam);
if (status == Status.SUCCESS) {
out.println("Your message has been successfully published on your Facebook wall!<br>");
} else if (status == Status.NOT_SPECIFIED_MESSAGE_OR_LINK) {
out.println("Either message or link needs to be specified!<br>");
} else if (status == Status.FACEBOOK_ERROR_INSUFFICIENT_SCOPE) {
String neededScope = "publish_stream";
out.println("You have insufficient privileges (Facebook scope) to publish message on your FB wall. Your access token need to have scope: <b>" + neededScope + "</b><br>");
// Create URL for start OAuth2 flow with custom scope added
PortletURL actionURL = response.createActionURL();
actionURL.setParameter(ActionRequest.ACTION_NAME, AbstractSocialPortlet.ACTION_OAUTH_REDIRECT);
actionURL.setParameter(OAuthConstants.PARAM_CUSTOM_SCOPE, neededScope);
out.println("Click <a style=\"color: blue;\" href=\"" + actionURL + "\">here</a> to fix it<br>");
} else if (status == Status.FACEBOOK_ERROR_OTHER) {
String errorMessage = request.getParameter(RENDER_PARAM_ERROR_MESSAGE);
out.println("Error occured during facebook processing. Error details: " + errorMessage + "<br>");
}
PortletURL backURL = response.createActionURL();
backURL.setParameter(ActionRequest.ACTION_NAME, ACTION_BACK);
out.println("<a style=\"color: blue;\" href=\"" + backURL + "\">Back</a><br>");
return;
}
PortletURL url = response.createActionURL();
url.setParameter(ActionRequest.ACTION_NAME, ACTION_UPDATE_STATUS);
// TODO: jsp?
out.println("<h3>Publish some content to your facebook wall</h3>");
out.println("<div style=\"font-size: 13px;\">Either message or link are required fields</div><br>");
out.println("<form method=\"POST\" action=\"" + url + "\">");
out.println("<table>");
out.println(renderInput("message", true, session));
out.println("<tr><td></td><td></td></tr>");
out.println("<tr><td colspan=2><div style=\"font-size: 13px;\">Other parameters, which are important only if you want to publish some link</div></td></tr>");
out.println(renderInput("link", true, session));
out.println(renderInput("picture", false, session));
out.println(renderInput("name", false, session));
out.println(renderInput("caption", false, session));
out.println(renderInput("description", false, session));
out.println("</table>");
out.println("<input type=\"submit\" value=\"submit\" />");
out.println("</form>");
// Save FB AccessToken to session, so it could be used in actionUpdateStatus
request.getPortletSession().setAttribute(ATTR_FB_ACCESS_TOKEN, accessToken);
}
|
diff --git a/src/main/java/com/tadamski/arij/issue/list/filters/DefaultFilters.java b/src/main/java/com/tadamski/arij/issue/list/filters/DefaultFilters.java
index 5425b0c..563c037 100644
--- a/src/main/java/com/tadamski/arij/issue/list/filters/DefaultFilters.java
+++ b/src/main/java/com/tadamski/arij/issue/list/filters/DefaultFilters.java
@@ -1,35 +1,36 @@
package com.tadamski.arij.issue.list.filters;
import com.googlecode.androidannotations.annotations.EBean;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: tmszdmsk
* Date: 26.06.13
* Time: 19:13
* To change this template use File | Settings | File Templates.
*/
@EBean
public class DefaultFilters {
public List<Filter> getFilterList() {
ArrayList<Filter> filters = new ArrayList<Filter>();
filters.add(new Filter("localMyOpenIssues","My open issues", "assignee = currentUser() AND resolution = Unresolved ORDER BY updatedDate DESC"));
filters.add(new Filter("localReportedByMe","Reported by me", "reporter = currentUser() ORDER BY createdDate DESC"));
filters.add(new Filter("localAllIssues","All issues", "ORDER BY createdDate DESC"));
filters.add(new Filter("localOpenBugz","Open bugs", "type = Bug and resolution is empty"));
+ filters.add(new Filter("localWatchedIssues", "Watched Issues", "watcher = currentUser() ORDER BY updatedDate DESC"));
return filters;
}
public Filter getFilter(String id){
for(Filter f: getFilterList()){
if(f.id.equals(id)){
return f;
}
}
return null;
}
}
| true | true | public List<Filter> getFilterList() {
ArrayList<Filter> filters = new ArrayList<Filter>();
filters.add(new Filter("localMyOpenIssues","My open issues", "assignee = currentUser() AND resolution = Unresolved ORDER BY updatedDate DESC"));
filters.add(new Filter("localReportedByMe","Reported by me", "reporter = currentUser() ORDER BY createdDate DESC"));
filters.add(new Filter("localAllIssues","All issues", "ORDER BY createdDate DESC"));
filters.add(new Filter("localOpenBugz","Open bugs", "type = Bug and resolution is empty"));
return filters;
}
| public List<Filter> getFilterList() {
ArrayList<Filter> filters = new ArrayList<Filter>();
filters.add(new Filter("localMyOpenIssues","My open issues", "assignee = currentUser() AND resolution = Unresolved ORDER BY updatedDate DESC"));
filters.add(new Filter("localReportedByMe","Reported by me", "reporter = currentUser() ORDER BY createdDate DESC"));
filters.add(new Filter("localAllIssues","All issues", "ORDER BY createdDate DESC"));
filters.add(new Filter("localOpenBugz","Open bugs", "type = Bug and resolution is empty"));
filters.add(new Filter("localWatchedIssues", "Watched Issues", "watcher = currentUser() ORDER BY updatedDate DESC"));
return filters;
}
|
diff --git a/src/main/java/edu/ucla/sspace/lsa/LatentSemanticAnalysis.java b/src/main/java/edu/ucla/sspace/lsa/LatentSemanticAnalysis.java
index 7333960b..98734e1b 100644
--- a/src/main/java/edu/ucla/sspace/lsa/LatentSemanticAnalysis.java
+++ b/src/main/java/edu/ucla/sspace/lsa/LatentSemanticAnalysis.java
@@ -1,568 +1,568 @@
/*
* Copyright 2009 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
*
* The S-Space package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.ucla.sspace.lsa;
import edu.ucla.sspace.basis.BasisMapping;
import edu.ucla.sspace.basis.StringBasisMapping;
import edu.ucla.sspace.common.GenericTermDocumentVectorSpace;
import edu.ucla.sspace.matrix.ArrayMatrix;
import edu.ucla.sspace.matrix.DiagonalMatrix;
import edu.ucla.sspace.matrix.LogEntropyTransform;
import edu.ucla.sspace.matrix.Matrices;
import edu.ucla.sspace.matrix.Matrix;
import edu.ucla.sspace.matrix.MatrixFile;
import edu.ucla.sspace.matrix.SVD;
import edu.ucla.sspace.matrix.Transform;
import edu.ucla.sspace.matrix.factorization.SingularValueDecomposition;
import edu.ucla.sspace.text.Document;
import edu.ucla.sspace.text.IteratorFactory;
import edu.ucla.sspace.util.Counter;
import edu.ucla.sspace.util.LoggerUtil;
import edu.ucla.sspace.util.ObjectCounter;
import edu.ucla.sspace.vector.DenseVector;
import edu.ucla.sspace.vector.DoubleVector;
import edu.ucla.sspace.vector.SparseDoubleVector;
import edu.ucla.sspace.vector.SparseHashDoubleVector;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* An implementation of Latent Semantic Analysis (LSA). This implementation is
* based on two papers.
* <ul>
*
* <li style="font-family:Garamond, Georgia, serif"> Landauer, T. K., Foltz,
* P. W., and Laham, D. (1998). Introduction to Latent Semantic
* Analysis. <i>Discourse Processes</i>, <b>25</b>, 259-284. Available <a
* href="http://lsa.colorado.edu/papers/dp1.LSAintro.pdf">here</a> </li>
*
* <li style="font-family:Garamond, Georgia, serif"> Landauer, T. K., and
* Dumais, S. T. (1997). A solution to Plato's problem: The Latent Semantic
* Analysis theory of the acquisition, induction, and representation of
* knowledge. <i>Psychological Review</i>, <b>104</b>, 211-240. Available
* <a href="http://lsa.colorado.edu/papers/plato/plato.annote.html">here</a>
* </li>
*
* </ul> See the Wikipedia page on <a
* href="http://en.wikipedia.org/wiki/Latent_semantic_analysis"> Latent Semantic
* Analysis </a> for an execuative summary.
*
* <p>
*
* LSA first processes documents into a word-document matrix where each unique
* word is a assigned a row in the matrix, and each column represents a
* document. The values of ths matrix correspond to the number of times the
* row's word occurs in the column's document. After the matrix has been built,
* the <a
* href="http://en.wikipedia.org/wiki/Singular_value_decomposition">Singular
* Value Decomposition</a> (SVD) is used to reduce the dimensionality of the
* original word-document matrix, denoted as <span style="font-family:Garamond,
* Georgia, serif">A</span>. The SVD is a way of factoring any matrix A into
* three matrices <span style="font-family:Garamond, Georgia, serif">U Σ
* V<sup>T</sup></span> such that <span style="font-family:Garamond, Georgia,
* serif"> Σ </span> is a diagonal matrix containing the singular values
* of <span style="font-family:Garamond, Georgia, serif">A</span>. The singular
* values of <span style="font-family:Garamond, Georgia, serif"> Σ </span>
* are ordered according to which causes the most variance in the values of
* <span style="font-family:Garamond, Georgia, serif">A</span>. The original
* matrix may be approximated by recomputing the matrix with only <span
* style="font-family:Garamond, Georgia, serif">k</span> of these singular
* values and setting the rest to 0. The approximated matrix <span
* style="font-family:Garamond, Georgia, serif"> Â = U<sub>k</sub>
* Σ<sub>k</sub> V<sub>k</sub><sup>T</sup></span> is the least squares
* best-fit rank-<span style="font-family:Garamond, Georgia, serif">k</span>
* approximation of <span style="font-family:Garamond, Georgia, serif">A</span>.
* LSA reduces the dimensions by keeping only the first <span
* style="font-family:Garamond, Georgia, serif">k</span> dimensions from the row
* vectors of <span style="font-family:Garamond, Georgia, serif">U</span>.
* These vectors form the <i>semantic space</i> of the words.
*
* <p>
*
* This class offers configurable preprocessing and dimensionality reduction.
* through three parameters. These properties should be specified in the {@code
* Properties} object passed to the {@link #processSpace(Properties)
* processSpace} method.
*
* <dl style="margin-left: 1em">
*
* <dt> <i>Property:</i> <code><b>{@value #MATRIX_TRANSFORM_PROPERTY}
* </b></code> <br>
* <i>Default:</i> {@link LogEntropyTransform}
*
* <dd style="padding-top: .5em">This variable sets the preprocessing algorithm
* to use on the term-document matrix prior to computing the SVD. The
* property value should be the fully qualified named of a class that
* implements {@link Transform}. The class should be public, not abstract,
* and should provide a public no-arg constructor.<p>
*
* <dt> <i>Property:</i> <code><b>{@value LSA_DIMENSIONS_PROPERTY}
* </b></code> <br>
* <i>Default:</i> {@code 300}
*
* <dd style="padding-top: .5em">The number of dimensions to use for the
* semantic space. This value is used as input to the SVD.<p>
*
* <dt> <i>Property:</i> <code><b>{@value LSA_SVD_ALGORITHM_PROPERTY}
* </b></code> <br>
* <i>Default:</i> {@link edu.ucla.sspace.matrix.SVD.Algorithm#ANY}
*
* <dd style="padding-top: .5em">This property sets the specific SVD algorithm
* that LSA will use to reduce the dimensionality of the word-document
* matrix. In general, users should not need to set this property, as the
* default behavior will choose the fastest available on the system.<p>
*
* <dt> <i>Property:</i> <code><b>{@value RETAIN_DOCUMENT_SPACE_PROPERTY}
* </b></code> <br>
* <i>Default:</i> {@code false}
*
* <dd style="padding-top: .5em">This property indicate whether the document
* space should be retained after {@code processSpace}. Setting this
* property to {@code true} will enable the {@link #getDocumentVector(int)
* getDocumentVector} method. <p>
*
* </dl> <p>
*
* <p>
*
* This class is thread-safe for concurrent calls of {@link
* #processDocument(BufferedReader) processDocument}. Once {@link
* #processSpace(Properties) processSpace} has been called, no further calls to
* {@code processDocument} should be made. This implementation does not support
* access to the semantic vectors until after {@code processSpace} has been
* called.
*
* @see Transform
* @see SingularValueDecomposition
*
* @author David Jurgens
*/
public class LatentSemanticAnalysis extends GenericTermDocumentVectorSpace
implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* The prefix for naming publically accessible properties
*/
private static final String PROPERTY_PREFIX =
"edu.ucla.sspace.lsa.LatentSemanticAnalysis";
/**
* The property to define the {@link Transform} class to be used
* when processing the space after all the documents have been seen.
*/
public static final String MATRIX_TRANSFORM_PROPERTY =
PROPERTY_PREFIX + ".transform";
/**
* The property to set the number of dimension to which the space should be
* reduced using the SVD
*/
public static final String LSA_DIMENSIONS_PROPERTY =
PROPERTY_PREFIX + ".dimensions";
/**
* The property to set the specific SVD algorithm used by an instance during
* {@code processSpace}. The value should be the name of a {@link
* edu.ucla.sspace.matrix.SVD.Algorithm}. If this property is unset, any
* available algorithm will be used according to the ordering defined in
* {@link SVD}.
*/
public static final String LSA_SVD_ALGORITHM_PROPERTY =
PROPERTY_PREFIX + ".svd.algorithm";
/**
* The property whose boolean value indicate whether the document space
* should be retained after {@code processSpace}. Setting this property to
* {@code true} will enable the {@link #getDocumentVector(int)
* getDocumentVector} method.
*/
public static final String RETAIN_DOCUMENT_SPACE_PROPERTY =
PROPERTY_PREFIX + ".retainDocSpace";
/**
* The name prefix used with {@link #getName()}
*/
private static final String LSA_SSPACE_NAME =
"lsa-semantic-space";
/**
* The document space of the term document based word space If the word
* space is reduced. After reduction it is the right factor matrix of the
* SVD of the word-document matrix. This matrix is only available after the
* {@link #processSpace(Transform, SVD.Algorithm, int, boolean)
* processSpace} method has been called.
*/
private Matrix documentSpace;
/**
* The diagonal matrix of the singular values
*/
private Matrix sigma;
/**
* The precomputed result of U * Sigma^-1, which is used to project new
* document vectors into the latent document space. Since this matrix is
* potentially large and its use only depends on the number of calls to
* {@link #project(Document)}, we cache the results with a {@code
* WeakReference}, letting the result be garbage collected if memory
* pressure gets too high.
*/
private transient WeakReference<Matrix> UtimesSigmaInvRef;
/**
* The left factor matrix of the SVD operation, which is the word space
* prior to be multiplied by the singular values.
*/
private Matrix U;
/**
* The {@link SingularValueDecomposition} algorithm that will decompose the word by
* document feature space into two smaller feature spaces: a word by class
* feature space and a class by feature space.
*/
private final SingularValueDecomposition reducer;
/**
* The {@link Transform} applied to the term document matrix prior to being
* reduced.
*/
private final Transform transform;
/**
* The final number of latent classes that will be used to represent the
* word space.
*/
private final int dimensions;
/**
* Set the true if the reduced document space will be made accessible.
*/
private final boolean retainDocumentSpace;
/**
* Creates a new {@link LatentSemanticAnalysis} instance. This intializes
* {@Link LatentSemanticAnalysis} with the default parameters set in the
* original paper. This construct initializes this instance such that the
* document space is <i>not</i> retained.
*/
public LatentSemanticAnalysis() throws IOException {
this(false, 300, new LogEntropyTransform(),
SVD.getFastestAvailableFactorization(),
false, new StringBasisMapping());
}
/**
* Creates a new {@link LatentSemanticAnalysis} instance with the specified
* number of dimensions. This intializes {@Link LatentSemanticAnalysis}
* with the default parameters set in the original paper for all other
* parameter values. This construct initializes this instance such that the
* document space is <i>not</i> retained.
*
* @param dimensions The number of dimensions to retain in the reduced space
*/
public LatentSemanticAnalysis(int numDimensions) throws IOException {
this(false, numDimensions, new LogEntropyTransform(),
SVD.getFastestAvailableFactorization(),
false, new StringBasisMapping());
}
/**
* Creates a new {@link LatentSemanticAnalysis} instance with the specified
* number of dimensions, using the specified method for performing the SVD.
* This intializes {@Link LatentSemanticAnalysis} with the default
* parameters set in the original paper for all other parameter values.
* This construct initializes this instance such that the document space is
* <i>not</i> retained.
*
* @param dimensions The number of dimensions to retain in the reduced space
*/
public LatentSemanticAnalysis(int numDimensions,
SingularValueDecomposition svdMethod)
throws IOException {
this(false, numDimensions, new LogEntropyTransform(),
svdMethod,
false, new StringBasisMapping());
}
/**
* Creates a new {@link LatentSemanticAnalysis} instance with the specified
* number of dimensions, which optionally retains both the word and document
* spaces. This intializes {@Link LatentSemanticAnalysis} with the default
* parameters set in the original paper for all other parameter values.
*
* @param dimensions The number of dimensions to retain in the reduced space
* @param retainDocumentSpace If true, the document space will be made
* accessible
*/
public LatentSemanticAnalysis(int numDimensions,
boolean retainDocumentSpace)
throws IOException {
this(retainDocumentSpace, numDimensions, new LogEntropyTransform(),
SVD.getFastestAvailableFactorization(),
false, new StringBasisMapping());
}
/**
* Constructs a new {@code LatentSemanticAnalysis} using the provided
* objects for processing.
*
* @param retainDocumentSpace If true, the document space will be made
* accessible
* @param dimensions The number of dimensions to retain in the reduced space
* @param transform The {@link Transform} to apply before reduction
* @param reducer The {@link SingularValueDecomposition} algorithm to
* apply to reduce the transformed term document matrix
* @param readHeaderToken If true, the first token of each document will be
* read and passed to {@link #handleDocumentHeader(int, String)
* handleDocumentHeader}, which discards the header
* @param termToIndex The {@link ConcurrentMap} used to map strings to
* indices
*
* @throws IOException if this instance encounters any errors when creatng
* the backing array files required for processing
*/
public LatentSemanticAnalysis(boolean retainDocumentSpace,
int dimensions,
Transform transform,
SingularValueDecomposition reducer,
boolean readHeaderToken,
BasisMapping<String, String> termToIndex)
throws IOException {
super(readHeaderToken, termToIndex, reducer.getBuilder());
this.reducer = reducer;
this.transform = transform;
this.dimensions = dimensions;
this.retainDocumentSpace = retainDocumentSpace;
}
/**
* {@inheritDoc}
*/
public String getSpaceName() {
return LSA_SSPACE_NAME;
}
/**
* Returns the semantics of the document as represented by a numeric vector.
* Note that document semantics may be represented in an entirely different
* space, so the corresponding semantic dimensions in the word space will be
* completely unrelated. However, document vectors may be compared to find
* those document with similar content.
*
* </p>
*
* Similar to {@code getVector}, this method is only to be used after {@code
* processSpace} has been called. By default, the document space is not
* retained unless {@code retainDocumentSpace} is set to true.
*
* </p>
*
* Implementation note: If a specific document ordering is needed, caution
* should be used when using this class in a multi-threaded environment.
* Beacuse the document number is based on what order it was
* <i>processed</i>, no guarantee is made that this will correspond with the
* original document ordering as it exists in the corpus files. However, in
* a single-threaded environment, the ordering will be preserved.
*
* @param documentNumber the number of the document according to when it was
* processed
*
* @return the semantics of the document in the document space.
* @throws IllegalArgumentException If the document space was not retained
* or the document number is out of range.
*/
public DoubleVector getDocumentVector(int documentNumber) {
if (documentSpace == null)
throw new IllegalArgumentException(
"The document space has not been retained or generated.");
if (documentNumber < 0 || documentNumber >= documentSpace.rows()) {
throw new IllegalArgumentException(
"Document number is not within the bounds of the number of "
+ "documents: " + documentNumber);
}
return documentSpace.getRowVector(documentNumber);
}
/**
* Returns the number of documents processed by {@link
* LatentSemanticAnalysis} if the document space has been retained.
*
* @throws IllegalArgumentException If the document space has not been
* retained.
*/
public int documentSpaceSize() {
if (documentSpace == null)
throw new IllegalArgumentException(
"The document space has not been retained or generated.");
return documentSpace.rows();
}
/**
* {@inheritDoc}
*
* @param properties {@inheritDoc} See this class's {@link
* LatentSemanticAnalysis javadoc} for the full list of supported
* properties.
*/
public void processSpace(Properties properties) {
// Perform any optional transformations (e.g., tf-idf) on the
// term-document matrix
MatrixFile processedSpace = processSpace(transform);
LoggerUtil.info(LOG, "reducing to %d dimensions", dimensions);
// Compute the SVD on the term-document space
reducer.factorize(processedSpace, dimensions);
wordSpace = reducer.dataClasses();
U = reducer.getLeftVectors();
sigma = reducer.getSingularValues();
// Save the reduced document space if requested.
if (retainDocumentSpace) {
LoggerUtil.verbose(LOG, "loading in document space");
// We transpose the document space to provide easier access to
// the document vectors, which in the un-transposed version are
// the columns.
documentSpace = Matrices.transpose(reducer.classFeatures());
}
}
/**
* Projects this document into the latent document space based on the
* distirbution of terms contained within it
*
* @param doc A document whose contents are to be mapped into the latent
* document space of this instance. The contents of this document
* are tokenized using the existing {@link IteratorFactory} settings.
* Note that tokens that are not in the word space of this {@link
* LatentSemanticAnalysis} instance will be ignored, so documents
* that consist mostly of unseen terms will likely not be represented
* well.
*
* @return the projected version of {@code doc} in this instances latent
* document space, using the recognized terms in the document
*
* @throws IllegalStateException if {@link #processSpace(Properties)} has
* not yet been called (that is, no latent document space exists
* yet).
*/
public DoubleVector project(Document doc) {
// Check that we can actually project the document
if (wordSpace == null)
throw new IllegalStateException(
"processSpace has not been called, so the latent document " +
"space does not yet exist");
// Tokenize the document using the existing tokenization rules
Iterator<String> docTokens =
IteratorFactory.tokenize(doc.reader());
// Ensure that when we are projecting the new document that we do not
// add any new terms to this space's basis.
termToIndex.setReadOnly(true);
int numDims = termToIndex.numDimensions();
// Iterate through the document's tokens and build the document
// representation for those terms that have an existing basis in the
// space
SparseDoubleVector docVec = new SparseHashDoubleVector(numDims);
while (docTokens.hasNext()) {
int dim = termToIndex.getDimension(docTokens.next());
if (dim >= 0)
docVec.add(dim, 1d);
}
// Transform the vector according to this instance's transform's state,
// which should normalize the vector as the original vectors were.
DoubleVector transformed = transform.transform(docVec);
// Represent the document as a 1-column matrix
Matrix queryAsMatrix = new ArrayMatrix(1, numDims);
for (int nz : docVec.getNonZeroIndices())
- queryAsMatrix.set(0, nz, docVec.get(nz));
+ queryAsMatrix.set(0, nz, transformed.get(nz));
// Project the new document vector, d, by using
//
// d * U_k * Sigma_k^-1
//
// where k is the dimensionality of the LSA space
Matrix UtimesSigmaInv = null;
// We cache the reuslts of the U_k * Sigma_k^-1 multiplication since
// this will be the same for all projections.
while (UtimesSigmaInv == null) {
if (UtimesSigmaInvRef != null
&& ((UtimesSigmaInv = UtimesSigmaInvRef.get()) != null))
break;
int rows = sigma.rows();
double[] sigmaInv = new double[rows];
for (int i = 0; i < rows; ++i)
sigmaInv[i] = 1d / sigma.get(i, i);
DiagonalMatrix sigmaInvMatrix = new DiagonalMatrix(sigmaInv);
UtimesSigmaInv =
Matrices.multiply(U, sigmaInvMatrix);
// Update the field with the new reference to the precomputed matrix
UtimesSigmaInvRef = new WeakReference<Matrix>(UtimesSigmaInv);
}
// Compute the resulting projected vector as a matrix
Matrix result = Matrices.multiply(queryAsMatrix, UtimesSigmaInv);
// Copy out the vector itself so that we don't retain a reference to the
// matrix as a result of its getRowVector call, which isn't guaranteed
// to return a copy.
int cols = result.columns();
DoubleVector projected = new DenseVector(result.columns());
for (int i = 0; i < cols; ++i)
projected.set(i, result.get(0, i));
return projected;
}
}
| true | true | public DoubleVector project(Document doc) {
// Check that we can actually project the document
if (wordSpace == null)
throw new IllegalStateException(
"processSpace has not been called, so the latent document " +
"space does not yet exist");
// Tokenize the document using the existing tokenization rules
Iterator<String> docTokens =
IteratorFactory.tokenize(doc.reader());
// Ensure that when we are projecting the new document that we do not
// add any new terms to this space's basis.
termToIndex.setReadOnly(true);
int numDims = termToIndex.numDimensions();
// Iterate through the document's tokens and build the document
// representation for those terms that have an existing basis in the
// space
SparseDoubleVector docVec = new SparseHashDoubleVector(numDims);
while (docTokens.hasNext()) {
int dim = termToIndex.getDimension(docTokens.next());
if (dim >= 0)
docVec.add(dim, 1d);
}
// Transform the vector according to this instance's transform's state,
// which should normalize the vector as the original vectors were.
DoubleVector transformed = transform.transform(docVec);
// Represent the document as a 1-column matrix
Matrix queryAsMatrix = new ArrayMatrix(1, numDims);
for (int nz : docVec.getNonZeroIndices())
queryAsMatrix.set(0, nz, docVec.get(nz));
// Project the new document vector, d, by using
//
// d * U_k * Sigma_k^-1
//
// where k is the dimensionality of the LSA space
Matrix UtimesSigmaInv = null;
// We cache the reuslts of the U_k * Sigma_k^-1 multiplication since
// this will be the same for all projections.
while (UtimesSigmaInv == null) {
if (UtimesSigmaInvRef != null
&& ((UtimesSigmaInv = UtimesSigmaInvRef.get()) != null))
break;
int rows = sigma.rows();
double[] sigmaInv = new double[rows];
for (int i = 0; i < rows; ++i)
sigmaInv[i] = 1d / sigma.get(i, i);
DiagonalMatrix sigmaInvMatrix = new DiagonalMatrix(sigmaInv);
UtimesSigmaInv =
Matrices.multiply(U, sigmaInvMatrix);
// Update the field with the new reference to the precomputed matrix
UtimesSigmaInvRef = new WeakReference<Matrix>(UtimesSigmaInv);
}
// Compute the resulting projected vector as a matrix
Matrix result = Matrices.multiply(queryAsMatrix, UtimesSigmaInv);
// Copy out the vector itself so that we don't retain a reference to the
// matrix as a result of its getRowVector call, which isn't guaranteed
// to return a copy.
int cols = result.columns();
DoubleVector projected = new DenseVector(result.columns());
for (int i = 0; i < cols; ++i)
projected.set(i, result.get(0, i));
return projected;
}
| public DoubleVector project(Document doc) {
// Check that we can actually project the document
if (wordSpace == null)
throw new IllegalStateException(
"processSpace has not been called, so the latent document " +
"space does not yet exist");
// Tokenize the document using the existing tokenization rules
Iterator<String> docTokens =
IteratorFactory.tokenize(doc.reader());
// Ensure that when we are projecting the new document that we do not
// add any new terms to this space's basis.
termToIndex.setReadOnly(true);
int numDims = termToIndex.numDimensions();
// Iterate through the document's tokens and build the document
// representation for those terms that have an existing basis in the
// space
SparseDoubleVector docVec = new SparseHashDoubleVector(numDims);
while (docTokens.hasNext()) {
int dim = termToIndex.getDimension(docTokens.next());
if (dim >= 0)
docVec.add(dim, 1d);
}
// Transform the vector according to this instance's transform's state,
// which should normalize the vector as the original vectors were.
DoubleVector transformed = transform.transform(docVec);
// Represent the document as a 1-column matrix
Matrix queryAsMatrix = new ArrayMatrix(1, numDims);
for (int nz : docVec.getNonZeroIndices())
queryAsMatrix.set(0, nz, transformed.get(nz));
// Project the new document vector, d, by using
//
// d * U_k * Sigma_k^-1
//
// where k is the dimensionality of the LSA space
Matrix UtimesSigmaInv = null;
// We cache the reuslts of the U_k * Sigma_k^-1 multiplication since
// this will be the same for all projections.
while (UtimesSigmaInv == null) {
if (UtimesSigmaInvRef != null
&& ((UtimesSigmaInv = UtimesSigmaInvRef.get()) != null))
break;
int rows = sigma.rows();
double[] sigmaInv = new double[rows];
for (int i = 0; i < rows; ++i)
sigmaInv[i] = 1d / sigma.get(i, i);
DiagonalMatrix sigmaInvMatrix = new DiagonalMatrix(sigmaInv);
UtimesSigmaInv =
Matrices.multiply(U, sigmaInvMatrix);
// Update the field with the new reference to the precomputed matrix
UtimesSigmaInvRef = new WeakReference<Matrix>(UtimesSigmaInv);
}
// Compute the resulting projected vector as a matrix
Matrix result = Matrices.multiply(queryAsMatrix, UtimesSigmaInv);
// Copy out the vector itself so that we don't retain a reference to the
// matrix as a result of its getRowVector call, which isn't guaranteed
// to return a copy.
int cols = result.columns();
DoubleVector projected = new DenseVector(result.columns());
for (int i = 0; i < cols; ++i)
projected.set(i, result.get(0, i));
return projected;
}
|
diff --git a/src/main/java/me/iffa/bspace/commands/SpaceHelpCommand.java b/src/main/java/me/iffa/bspace/commands/SpaceHelpCommand.java
index 247ef6b..f2dd8c6 100644
--- a/src/main/java/me/iffa/bspace/commands/SpaceHelpCommand.java
+++ b/src/main/java/me/iffa/bspace/commands/SpaceHelpCommand.java
@@ -1,41 +1,41 @@
// Package Declaration
package me.iffa.bspace.commands;
// bSpace Imports
import me.iffa.bspace.Space;
// Bukkit Imports
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
/**
* Represents "/space help".
*
* @author iffa
*/
public class SpaceHelpCommand extends SpaceCommand {
/**
* Constructor of SpaceHelpCommand.
*
* @param plugin bSpace instance
* @param sender Command sender
* @param args Command arguments
*/
public SpaceHelpCommand(Space plugin, CommandSender sender, String[] args) {
super(plugin, sender, args);
}
/**
* Does the command.
*/
@Override
public void command() {
sender.sendMessage(ChatColor.DARK_GREEN + "[bSpace] Usage:");
sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)");
sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space");
sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds");
sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message");
sender.sendMessage(ChatColor.GREEN + "/space about - About bSpace");
- sender.sendMessage(ChatColor.DARK_GREEN + "If you have questions, please visit " + ChatColor.GRAY + "bit.ly/bSpace" + ChatColor.DARK_GREEN + "!");
+ sender.sendMessage(ChatColor.DARK_GREEN + "If you have questions, please visit " + ChatColor.GRAY + "bit.ly/banspace" + ChatColor.DARK_GREEN + "!");
}
}
| true | true | public void command() {
sender.sendMessage(ChatColor.DARK_GREEN + "[bSpace] Usage:");
sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)");
sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space");
sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds");
sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message");
sender.sendMessage(ChatColor.GREEN + "/space about - About bSpace");
sender.sendMessage(ChatColor.DARK_GREEN + "If you have questions, please visit " + ChatColor.GRAY + "bit.ly/bSpace" + ChatColor.DARK_GREEN + "!");
}
| public void command() {
sender.sendMessage(ChatColor.DARK_GREEN + "[bSpace] Usage:");
sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)");
sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space");
sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds");
sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message");
sender.sendMessage(ChatColor.GREEN + "/space about - About bSpace");
sender.sendMessage(ChatColor.DARK_GREEN + "If you have questions, please visit " + ChatColor.GRAY + "bit.ly/banspace" + ChatColor.DARK_GREEN + "!");
}
|
diff --git a/src-pos/com/openbravo/pos/catalog/JCatalog.java b/src-pos/com/openbravo/pos/catalog/JCatalog.java
index ab80850..376c890 100644
--- a/src-pos/com/openbravo/pos/catalog/JCatalog.java
+++ b/src-pos/com/openbravo/pos/catalog/JCatalog.java
@@ -1,558 +1,559 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2008 Openbravo, S.L.
// http://sourceforge.net/projects/openbravopos
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.openbravo.pos.catalog;
import com.openbravo.pos.ticket.CategoryInfo;
import com.openbravo.pos.ticket.ProductInfoExt;
import com.openbravo.pos.util.ThumbNailBuilder;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.forms.DataLogicSales;
import com.openbravo.pos.sales.TaxesLogic;
import com.openbravo.pos.ticket.TaxInfo;
/**
*
* @author adrianromero
*/
public class JCatalog extends JPanel implements ListSelectionListener, CatalogSelector {
protected EventListenerList listeners = new EventListenerList();
private DataLogicSales m_dlSales;
private TaxesLogic taxeslogic;
private boolean pricevisible;
private boolean taxesincluded;
// Set of Products panels
private Map<String, ProductInfoExt> m_productsset = new HashMap<String, ProductInfoExt>();
// Set of Categoriespanels
private Set<String> m_categoriesset = new HashSet<String>();
private ThumbNailBuilder tnbbutton;
private ThumbNailBuilder tnbcat;
private CategoryInfo showingcategory = null;
/** Creates new form JCatalog */
public JCatalog(DataLogicSales dlSales) {
this(dlSales, false, false, 64, 54);
}
public JCatalog(DataLogicSales dlSales, boolean pricevisible, boolean taxesincluded, int width, int height) {
m_dlSales = dlSales;
this.pricevisible = pricevisible;
this.taxesincluded = taxesincluded;
initComponents();
m_jListCategories.addListSelectionListener(this);
m_jscrollcat.getVerticalScrollBar().setPreferredSize(new Dimension(35, 35));
tnbcat = new ThumbNailBuilder(32, 32, "com/openbravo/images/folder_yellow.png");
tnbbutton = new ThumbNailBuilder(width, height, "com/openbravo/images/package.png");
}
public Component getComponent() {
return this;
}
public void showCatalogPanel(String id) {
if (id == null) {
showRootCategoriesPanel();
} else {
showProductPanel(id);
}
}
public void loadCatalog() throws BasicException {
// delete all categories panel
m_jProducts.removeAll();
m_productsset.clear();
m_categoriesset.clear();
showingcategory = null;
// Load the taxes logic
taxeslogic = new TaxesLogic(m_dlSales.getTaxList().list());
// Load all categories.
java.util.List<CategoryInfo> categories = m_dlSales.getRootCategories();
// Select the first category
m_jListCategories.setCellRenderer(new SmallCategoryRenderer());
m_jListCategories.setModel(new CategoriesListModel(categories)); // aCatList
if (m_jListCategories.getModel().getSize() == 0) {
m_jscrollcat.setVisible(false);
jPanel2.setVisible(false);
} else {
m_jscrollcat.setVisible(true);
jPanel2.setVisible(true);
m_jListCategories.setSelectedIndex(0);
}
// Display catalog panel
showRootCategoriesPanel();
}
public void setComponentEnabled(boolean value) {
m_jListCategories.setEnabled(value);
m_jscrollcat.setEnabled(value);
m_jUp.setEnabled(value);
m_jDown.setEnabled(value);
m_lblIndicator.setEnabled(value);
m_btnBack.setEnabled(value);
m_jProducts.setEnabled(value);
synchronized (m_jProducts.getTreeLock()) {
int compCount = m_jProducts.getComponentCount();
for (int i = 0 ; i < compCount ; i++) {
m_jProducts.getComponent(i).setEnabled(value);
}
}
this.setEnabled(value);
}
public void addActionListener(ActionListener l) {
listeners.add(ActionListener.class, l);
}
public void removeActionListener(ActionListener l) {
listeners.remove(ActionListener.class, l);
}
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
int i = m_jListCategories.getSelectedIndex();
if (i >= 0) {
// Lo hago visible...
Rectangle oRect = m_jListCategories.getCellBounds(i, i);
m_jListCategories.scrollRectToVisible(oRect);
}
}
}
protected void fireSelectedProduct(ProductInfoExt prod) {
EventListener[] l = listeners.getListeners(ActionListener.class);
ActionEvent e = null;
for (int i = 0; i < l.length; i++) {
if (e == null) {
e = new ActionEvent(prod, ActionEvent.ACTION_PERFORMED, prod.getID());
}
((ActionListener) l[i]).actionPerformed(e);
}
}
private void selectCategoryPanel(String catid) {
try {
// Load categories panel if not exists
if (!m_categoriesset.contains(catid)) {
JCatalogTab jcurrTab = new JCatalogTab();
jcurrTab.applyComponentOrientation(getComponentOrientation());
m_jProducts.add(jcurrTab, catid);
m_categoriesset.add(catid);
// Add subcategories
java.util.List<CategoryInfo> categories = m_dlSales.getSubcategories(catid);
for (CategoryInfo cat : categories) {
jcurrTab.addButton(new ImageIcon(tnbbutton.getThumbNailText(cat.getImage(), cat.getName())), new SelectedCategory(cat));
}
// Add products
java.util.List<ProductInfoExt> products = m_dlSales.getProductCatalog(catid);
for (ProductInfoExt prod : products) {
jcurrTab.addButton(new ImageIcon(tnbbutton.getThumbNailText(prod.getImage(), getProductLabel(prod))), new SelectedAction(prod));
}
}
// Show categories panel
CardLayout cl = (CardLayout)(m_jProducts.getLayout());
cl.show(m_jProducts, catid);
} catch (BasicException e) {
JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
}
}
private String getProductLabel(ProductInfoExt product) {
if (pricevisible) {
if (taxesincluded) {
TaxInfo tax = taxeslogic.getTaxInfo(product.getTaxCategoryInfo());
return "<html><center>" + product.getName() + "<br>" + product.printPriceSellTax(tax);
} else {
return "<html><center>" + product.getName() + "<br>" + product.printPriceSell();
}
} else {
return product.getName();
}
}
private void selectIndicatorPanel(Icon icon, String label) {
m_lblIndicator.setText(label);
m_lblIndicator.setIcon(icon);
// Show subcategories panel
CardLayout cl = (CardLayout)(m_jCategories.getLayout());
cl.show(m_jCategories, "subcategories");
}
private void selectIndicatorCategories() {
// Show root categories panel
CardLayout cl = (CardLayout)(m_jCategories.getLayout());
cl.show(m_jCategories, "rootcategories");
}
private void showRootCategoriesPanel() {
selectIndicatorCategories();
// Show selected root category
CategoryInfo cat = (CategoryInfo) m_jListCategories.getSelectedValue();
if (cat != null) {
selectCategoryPanel(cat.getID());
}
showingcategory = null;
}
private void showSubcategoryPanel(CategoryInfo category) {
selectIndicatorPanel(new ImageIcon(tnbbutton.getThumbNail(category.getImage())), category.getName());
selectCategoryPanel(category.getID());
showingcategory = category;
}
private void showProductPanel(String id) {
ProductInfoExt product = m_productsset.get(id);
if (product == null) {
if (m_productsset.containsKey(id)) {
// It is an empty panel
if (showingcategory == null) {
showRootCategoriesPanel();
} else {
showSubcategoryPanel(showingcategory);
}
} else {
try {
// Create products panel
java.util.List<ProductInfoExt> products = m_dlSales.getProductComments(id);
if (products.size() == 0) {
// no hay productos por tanto lo anado a la de vacios y muestro el panel principal.
m_productsset.put(id, null);
if (showingcategory == null) {
showRootCategoriesPanel();
} else {
showSubcategoryPanel(showingcategory);
}
} else {
// Load product panel
product = m_dlSales.getProductInfo(id);
m_productsset.put(id, product);
JCatalogTab jcurrTab = new JCatalogTab();
jcurrTab.applyComponentOrientation(getComponentOrientation());
m_jProducts.add(jcurrTab, "PRODUCT." + id);
// Add products
for (ProductInfoExt prod : products) {
jcurrTab.addButton(new ImageIcon(tnbbutton.getThumbNailText(prod.getImage(), getProductLabel(prod))), new SelectedAction(prod));
}
selectIndicatorPanel(new ImageIcon(tnbbutton.getThumbNail(product.getImage())), product.getName());
CardLayout cl = (CardLayout)(m_jProducts.getLayout());
cl.show(m_jProducts, "PRODUCT." + id);
}
} catch (BasicException eb) {
eb.printStackTrace();
m_productsset.put(id, null);
if (showingcategory == null) {
showRootCategoriesPanel();
} else {
showSubcategoryPanel(showingcategory);
}
}
}
} else {
// already exists
selectIndicatorPanel(new ImageIcon(tnbbutton.getThumbNail(product.getImage())), product.getName());
CardLayout cl = (CardLayout)(m_jProducts.getLayout());
cl.show(m_jProducts, "PRODUCT." + id);
}
}
private class SelectedAction implements ActionListener {
private ProductInfoExt prod;
public SelectedAction(ProductInfoExt prod) {
this.prod = prod;
}
public void actionPerformed(ActionEvent e) {
fireSelectedProduct(prod);
}
}
private class SelectedCategory implements ActionListener {
private CategoryInfo category;
public SelectedCategory(CategoryInfo category) {
this.category = category;
}
public void actionPerformed(ActionEvent e) {
showSubcategoryPanel(category);
}
}
private class CategoriesListModel extends AbstractListModel {
private java.util.List m_aCategories;
public CategoriesListModel(java.util.List aCategories) {
m_aCategories = aCategories;
}
public int getSize() {
return m_aCategories.size();
}
public Object getElementAt(int i) {
return m_aCategories.get(i);
}
}
private class SmallCategoryRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus);
CategoryInfo cat = (CategoryInfo) value;
setText(cat.getName());
setIcon(new ImageIcon(tnbcat.getThumbNail(cat.getImage())));
return this;
}
}
/** 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() {
m_jCategories = new javax.swing.JPanel();
m_jRootCategories = new javax.swing.JPanel();
m_jscrollcat = new javax.swing.JScrollPane();
m_jListCategories = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
m_jUp = new javax.swing.JButton();
m_jDown = new javax.swing.JButton();
m_jSubCategories = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
m_lblIndicator = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
m_btnBack = new javax.swing.JButton();
m_jProducts = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
+ m_jCategories.setMaximumSize(new java.awt.Dimension(275, 600));
+ m_jCategories.setPreferredSize(new java.awt.Dimension(275, 600));
m_jCategories.setLayout(new java.awt.CardLayout());
m_jRootCategories.setLayout(new java.awt.BorderLayout());
m_jscrollcat.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
m_jscrollcat.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
- m_jscrollcat.setPreferredSize(new java.awt.Dimension(210, 0));
m_jListCategories.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
m_jListCategories.setFocusable(false);
m_jListCategories.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
m_jListCategoriesValueChanged(evt);
}
});
m_jscrollcat.setViewportView(m_jListCategories);
- m_jRootCategories.add(m_jscrollcat, java.awt.BorderLayout.LINE_START);
+ m_jRootCategories.add(m_jscrollcat, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel3.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_jUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1uparrow22.png"))); // NOI18N
m_jUp.setFocusPainted(false);
m_jUp.setFocusable(false);
m_jUp.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jUp.setRequestFocusEnabled(false);
m_jUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jUpActionPerformed(evt);
}
});
jPanel3.add(m_jUp);
m_jDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1downarrow22.png"))); // NOI18N
m_jDown.setFocusPainted(false);
m_jDown.setFocusable(false);
m_jDown.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jDown.setRequestFocusEnabled(false);
m_jDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jDownActionPerformed(evt);
}
});
jPanel3.add(m_jDown);
jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);
- m_jRootCategories.add(jPanel2, java.awt.BorderLayout.CENTER);
+ m_jRootCategories.add(jPanel2, java.awt.BorderLayout.LINE_END);
m_jCategories.add(m_jRootCategories, "rootcategories");
m_jSubCategories.setLayout(new java.awt.BorderLayout());
jPanel4.setLayout(new java.awt.BorderLayout());
m_lblIndicator.setText("jLabel1");
jPanel4.add(m_lblIndicator, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel4, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel5.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/3uparrow.png"))); // NOI18N
m_btnBack.setFocusPainted(false);
m_btnBack.setFocusable(false);
m_btnBack.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_btnBack.setRequestFocusEnabled(false);
m_btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_btnBackActionPerformed(evt);
}
});
jPanel5.add(m_btnBack);
jPanel1.add(jPanel5, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel1, java.awt.BorderLayout.LINE_END);
m_jCategories.add(m_jSubCategories, "subcategories");
add(m_jCategories, java.awt.BorderLayout.LINE_START);
m_jProducts.setLayout(new java.awt.CardLayout());
add(m_jProducts, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void m_btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_btnBackActionPerformed
showRootCategoriesPanel();
}//GEN-LAST:event_m_btnBackActionPerformed
private void m_jDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDownActionPerformed
int i = m_jListCategories.getSelectionModel().getMaxSelectionIndex();
if (i < 0){
i = 0; // No hay ninguna seleccionada
} else {
i ++;
if (i >= m_jListCategories.getModel().getSize() ) {
i = m_jListCategories.getModel().getSize() - 1;
}
}
if ((i >= 0) && (i < m_jListCategories.getModel().getSize())) {
// Solo seleccionamos si podemos.
m_jListCategories.getSelectionModel().setSelectionInterval(i, i);
}
}//GEN-LAST:event_m_jDownActionPerformed
private void m_jUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jUpActionPerformed
int i = m_jListCategories.getSelectionModel().getMinSelectionIndex();
if (i < 0){
i = m_jListCategories.getModel().getSize() - 1; // No hay ninguna seleccionada
} else {
i --;
if (i < 0) {
i = 0;
}
}
if ((i >= 0) && (i < m_jListCategories.getModel().getSize())) {
// Solo seleccionamos si podemos.
m_jListCategories.getSelectionModel().setSelectionInterval(i, i);
}
}//GEN-LAST:event_m_jUpActionPerformed
private void m_jListCategoriesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_m_jListCategoriesValueChanged
if (!evt.getValueIsAdjusting()) {
CategoryInfo cat = (CategoryInfo) m_jListCategories.getSelectedValue();
if (cat != null) {
selectCategoryPanel(cat.getID());
}
}
}//GEN-LAST:event_m_jListCategoriesValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JButton m_btnBack;
private javax.swing.JPanel m_jCategories;
private javax.swing.JButton m_jDown;
private javax.swing.JList m_jListCategories;
private javax.swing.JPanel m_jProducts;
private javax.swing.JPanel m_jRootCategories;
private javax.swing.JPanel m_jSubCategories;
private javax.swing.JButton m_jUp;
private javax.swing.JScrollPane m_jscrollcat;
private javax.swing.JLabel m_lblIndicator;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
m_jCategories = new javax.swing.JPanel();
m_jRootCategories = new javax.swing.JPanel();
m_jscrollcat = new javax.swing.JScrollPane();
m_jListCategories = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
m_jUp = new javax.swing.JButton();
m_jDown = new javax.swing.JButton();
m_jSubCategories = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
m_lblIndicator = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
m_btnBack = new javax.swing.JButton();
m_jProducts = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
m_jCategories.setLayout(new java.awt.CardLayout());
m_jRootCategories.setLayout(new java.awt.BorderLayout());
m_jscrollcat.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
m_jscrollcat.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
m_jscrollcat.setPreferredSize(new java.awt.Dimension(210, 0));
m_jListCategories.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
m_jListCategories.setFocusable(false);
m_jListCategories.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
m_jListCategoriesValueChanged(evt);
}
});
m_jscrollcat.setViewportView(m_jListCategories);
m_jRootCategories.add(m_jscrollcat, java.awt.BorderLayout.LINE_START);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel3.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_jUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1uparrow22.png"))); // NOI18N
m_jUp.setFocusPainted(false);
m_jUp.setFocusable(false);
m_jUp.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jUp.setRequestFocusEnabled(false);
m_jUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jUpActionPerformed(evt);
}
});
jPanel3.add(m_jUp);
m_jDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1downarrow22.png"))); // NOI18N
m_jDown.setFocusPainted(false);
m_jDown.setFocusable(false);
m_jDown.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jDown.setRequestFocusEnabled(false);
m_jDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jDownActionPerformed(evt);
}
});
jPanel3.add(m_jDown);
jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);
m_jRootCategories.add(jPanel2, java.awt.BorderLayout.CENTER);
m_jCategories.add(m_jRootCategories, "rootcategories");
m_jSubCategories.setLayout(new java.awt.BorderLayout());
jPanel4.setLayout(new java.awt.BorderLayout());
m_lblIndicator.setText("jLabel1");
jPanel4.add(m_lblIndicator, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel4, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel5.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/3uparrow.png"))); // NOI18N
m_btnBack.setFocusPainted(false);
m_btnBack.setFocusable(false);
m_btnBack.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_btnBack.setRequestFocusEnabled(false);
m_btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_btnBackActionPerformed(evt);
}
});
jPanel5.add(m_btnBack);
jPanel1.add(jPanel5, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel1, java.awt.BorderLayout.LINE_END);
m_jCategories.add(m_jSubCategories, "subcategories");
add(m_jCategories, java.awt.BorderLayout.LINE_START);
m_jProducts.setLayout(new java.awt.CardLayout());
add(m_jProducts, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
m_jCategories = new javax.swing.JPanel();
m_jRootCategories = new javax.swing.JPanel();
m_jscrollcat = new javax.swing.JScrollPane();
m_jListCategories = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
m_jUp = new javax.swing.JButton();
m_jDown = new javax.swing.JButton();
m_jSubCategories = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
m_lblIndicator = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
m_btnBack = new javax.swing.JButton();
m_jProducts = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
m_jCategories.setMaximumSize(new java.awt.Dimension(275, 600));
m_jCategories.setPreferredSize(new java.awt.Dimension(275, 600));
m_jCategories.setLayout(new java.awt.CardLayout());
m_jRootCategories.setLayout(new java.awt.BorderLayout());
m_jscrollcat.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
m_jscrollcat.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
m_jListCategories.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
m_jListCategories.setFocusable(false);
m_jListCategories.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
m_jListCategoriesValueChanged(evt);
}
});
m_jscrollcat.setViewportView(m_jListCategories);
m_jRootCategories.add(m_jscrollcat, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel3.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_jUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1uparrow22.png"))); // NOI18N
m_jUp.setFocusPainted(false);
m_jUp.setFocusable(false);
m_jUp.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jUp.setRequestFocusEnabled(false);
m_jUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jUpActionPerformed(evt);
}
});
jPanel3.add(m_jUp);
m_jDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/1downarrow22.png"))); // NOI18N
m_jDown.setFocusPainted(false);
m_jDown.setFocusable(false);
m_jDown.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_jDown.setRequestFocusEnabled(false);
m_jDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jDownActionPerformed(evt);
}
});
jPanel3.add(m_jDown);
jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);
m_jRootCategories.add(jPanel2, java.awt.BorderLayout.LINE_END);
m_jCategories.add(m_jRootCategories, "rootcategories");
m_jSubCategories.setLayout(new java.awt.BorderLayout());
jPanel4.setLayout(new java.awt.BorderLayout());
m_lblIndicator.setText("jLabel1");
jPanel4.add(m_lblIndicator, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel4, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
jPanel5.setLayout(new java.awt.GridLayout(0, 1, 0, 5));
m_btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/3uparrow.png"))); // NOI18N
m_btnBack.setFocusPainted(false);
m_btnBack.setFocusable(false);
m_btnBack.setMargin(new java.awt.Insets(8, 14, 8, 14));
m_btnBack.setRequestFocusEnabled(false);
m_btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_btnBackActionPerformed(evt);
}
});
jPanel5.add(m_btnBack);
jPanel1.add(jPanel5, java.awt.BorderLayout.NORTH);
m_jSubCategories.add(jPanel1, java.awt.BorderLayout.LINE_END);
m_jCategories.add(m_jSubCategories, "subcategories");
add(m_jCategories, java.awt.BorderLayout.LINE_START);
m_jProducts.setLayout(new java.awt.CardLayout());
add(m_jProducts, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/Player.java b/src/Player.java
index 9077c60..4fe843a 100644
--- a/src/Player.java
+++ b/src/Player.java
@@ -1,34 +1,34 @@
import java.util.ArrayList;
public class Player {
private String m_name;
private int m_bank;
private ArrayList<Card> m_hand;
- public Player(String name) {
- m_name = name;
+ public Player(String name) {
+ m_name = name;
m_bank = 0;
m_hand = new ArrayList<Card>();
- }
+ }
public void addBank(int n) {
m_bank += n;
}
public void removeBank(int n) {
m_bank -= n;
}
public int getBank() {
return m_bank;
}
public void deal(Card card) {
m_hand.add(card);
}
public ArrayList<Card> getHand() {
return m_hand;
}
}
| false | true | public Player(String name) {
m_name = name;
m_bank = 0;
m_hand = new ArrayList<Card>();
}
| public Player(String name) {
m_name = name;
m_bank = 0;
m_hand = new ArrayList<Card>();
}
|
diff --git a/Client.java b/Client.java
index 55542cd..2e9d11f 100644
--- a/Client.java
+++ b/Client.java
@@ -1,115 +1,115 @@
/* Client
Handles the client-side of communications - display messages sent from the server and accept messages
sent from the user and forward them to the server.
Still needs:
- Usage of proper Protocols.
- Exception handling
- More, I'm sure, but I can't think of it right now.
*/
import java.io.*; // Provides for system input and output through data
// streams, serialization and the file system
import java.net.*; // Provides the classes for implementing networking
// applications Lemons
// TCP Client class
class Client {
public static void main(String argv[]) throws Exception
{
int lisPort;
String hostname;
if(argv.length == 2)
{
hostname = argv[0];
lisPort = Integer.parseInt(argv[1]);
connect(hostname, lisPort);
} else
{
System.out.println("Please specify a hostname and port number.");
}
}
public static void connect(String hostname, int port) throws Exception
{
BufferedReader servIn;
PrintWriter servOut;
BufferedReader userIn;
Protocol protocol = new Protocol();
Socket clientSocket;
String userPkt = "";
String serverPkt = "";
String serverString = "";
String userString = "";
char[] data;
int dataLength;
String cmd_type;
userIn = new BufferedReader(new InputStreamReader(System.in));
- try
- {
+// try
+// {
// Create the socket and connect.
clientSocket = new Socket(hostname, port);
// Set up communication channels.
servOut = new PrintWriter(clientSocket.getOutputStream(), true);
servIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PROTOCOL
while(serverString != "END")
{
while(userString.equals("") && serverPkt.equals(""))
{
// Poll for input from either the user or the server continually.
if(userIn.ready())
userString = userIn.readLine();
else if(servIn.ready())
serverPkt = servIn.readLine();
}
if(userString.equals(""))
{
// The server sent us something ; display it.
dataLength = protocol.getLength(serverPkt);
data = new char[dataLength];
servIn.read(data, 0, dataLength);
serverString = new String(data);
System.out.println(serverString);
} else if(userString != null)
{
if(userString.indexOf(" ") != -1 && userString.indexOf(" ") != userString.length())
{
cmd_type = userString.substring(0, userString.indexOf(" "));
userString = userString.substring(userString.indexOf(" ") + 1);
} else
{
cmd_type = "LOGIN";
}
userPkt = protocol.makePacket(userString, cmd_type);
// The user typed something - send it to the server.
System.out.println("Sending " + userPkt);
servOut.println(userPkt);
}
serverPkt = "";
userPkt = "";
userString = "";
serverString = "";
}
// PROTOCOL
clientSocket.close();
- } catch(Exception ce)
- {
- System.out.println("There has been some difficulties. Check your port # and hostname please!");
- }
+// } catch(Exception ce)
+// {
+// System.out.println("There has been some difficulties. Check your port # and hostname please!");
+// }
}
}
| false | true | public static void connect(String hostname, int port) throws Exception
{
BufferedReader servIn;
PrintWriter servOut;
BufferedReader userIn;
Protocol protocol = new Protocol();
Socket clientSocket;
String userPkt = "";
String serverPkt = "";
String serverString = "";
String userString = "";
char[] data;
int dataLength;
String cmd_type;
userIn = new BufferedReader(new InputStreamReader(System.in));
try
{
// Create the socket and connect.
clientSocket = new Socket(hostname, port);
// Set up communication channels.
servOut = new PrintWriter(clientSocket.getOutputStream(), true);
servIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PROTOCOL
while(serverString != "END")
{
while(userString.equals("") && serverPkt.equals(""))
{
// Poll for input from either the user or the server continually.
if(userIn.ready())
userString = userIn.readLine();
else if(servIn.ready())
serverPkt = servIn.readLine();
}
if(userString.equals(""))
{
// The server sent us something ; display it.
dataLength = protocol.getLength(serverPkt);
data = new char[dataLength];
servIn.read(data, 0, dataLength);
serverString = new String(data);
System.out.println(serverString);
} else if(userString != null)
{
if(userString.indexOf(" ") != -1 && userString.indexOf(" ") != userString.length())
{
cmd_type = userString.substring(0, userString.indexOf(" "));
userString = userString.substring(userString.indexOf(" ") + 1);
} else
{
cmd_type = "LOGIN";
}
userPkt = protocol.makePacket(userString, cmd_type);
// The user typed something - send it to the server.
System.out.println("Sending " + userPkt);
servOut.println(userPkt);
}
serverPkt = "";
userPkt = "";
userString = "";
serverString = "";
}
// PROTOCOL
clientSocket.close();
} catch(Exception ce)
{
System.out.println("There has been some difficulties. Check your port # and hostname please!");
}
}
| public static void connect(String hostname, int port) throws Exception
{
BufferedReader servIn;
PrintWriter servOut;
BufferedReader userIn;
Protocol protocol = new Protocol();
Socket clientSocket;
String userPkt = "";
String serverPkt = "";
String serverString = "";
String userString = "";
char[] data;
int dataLength;
String cmd_type;
userIn = new BufferedReader(new InputStreamReader(System.in));
// try
// {
// Create the socket and connect.
clientSocket = new Socket(hostname, port);
// Set up communication channels.
servOut = new PrintWriter(clientSocket.getOutputStream(), true);
servIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// PROTOCOL
while(serverString != "END")
{
while(userString.equals("") && serverPkt.equals(""))
{
// Poll for input from either the user or the server continually.
if(userIn.ready())
userString = userIn.readLine();
else if(servIn.ready())
serverPkt = servIn.readLine();
}
if(userString.equals(""))
{
// The server sent us something ; display it.
dataLength = protocol.getLength(serverPkt);
data = new char[dataLength];
servIn.read(data, 0, dataLength);
serverString = new String(data);
System.out.println(serverString);
} else if(userString != null)
{
if(userString.indexOf(" ") != -1 && userString.indexOf(" ") != userString.length())
{
cmd_type = userString.substring(0, userString.indexOf(" "));
userString = userString.substring(userString.indexOf(" ") + 1);
} else
{
cmd_type = "LOGIN";
}
userPkt = protocol.makePacket(userString, cmd_type);
// The user typed something - send it to the server.
System.out.println("Sending " + userPkt);
servOut.println(userPkt);
}
serverPkt = "";
userPkt = "";
userString = "";
serverString = "";
}
// PROTOCOL
clientSocket.close();
// } catch(Exception ce)
// {
// System.out.println("There has been some difficulties. Check your port # and hostname please!");
// }
}
|
diff --git a/test-src/com/redhat/ceylon/compiler/java/test/interop/InteropTest.java b/test-src/com/redhat/ceylon/compiler/java/test/interop/InteropTest.java
index b4ad85bbe..5b082a5c1 100755
--- a/test-src/com/redhat/ceylon/compiler/java/test/interop/InteropTest.java
+++ b/test-src/com/redhat/ceylon/compiler/java/test/interop/InteropTest.java
@@ -1,186 +1,187 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.interop;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
public class InteropTest extends CompilerTest {
@Test
public void testIopArrays(){
compareWithJavaSource("Arrays");
}
@Test
public void testIopConstructors(){
compareWithJavaSource("Constructors");
}
@Test
public void testIopImport(){
compareWithJavaSource("Import");
}
@Test
public void testIopMethods(){
compile("JavaWithOverloadedMembers.java", "JavaWithOverloadedMembersSubClass.java");
compareWithJavaSource("Methods");
}
@Ignore("M3")
@Test
public void testIopImplementOverloadedMethods(){
compile("JavaWithOverloadedMembers.java", "JavaWithOverloadedMembersSubClass.java");
compareWithJavaSource("ImplementOverloadedMethods");
}
@Test
public void testIopFields(){
compile("JavaFields.java");
compareWithJavaSource("Fields");
}
@Test
public void testIopAttributes(){
compile("JavaBean.java");
compareWithJavaSource("Attributes");
}
@Test
public void testIopSatisfies(){
compile("JavaInterface.java");
compareWithJavaSource("Satisfies");
}
@Test
public void testIopStaticMembers(){
compile("JavaWithStaticMembers.java", "JavaWithStaticMembersSubClass.java");
compareWithJavaSource("StaticMembers");
}
@Test
public void testIopTypes(){
compareWithJavaSource("Types");
}
@Test
public void testIopCaseMismatch(){
compile("javaCaseMismatch.java");
compareWithJavaSource("CaseMismatch");
}
@Test
public void testIopCeylonKeywords(){
compile("satisfies.java");
compareWithJavaSource("CeylonKeywords");
}
@Test
public void testIopCheckedExceptions(){
compile("JavaCheckedExceptions.java");
compareWithJavaSource("CheckedExceptions");
}
@Test
public void testIopRefinesProtectedAccessMethod(){
compile("access/JavaAccessModifiers.java");
compareWithJavaSource("access/RefinesProtectedAccessMethod");
}
@Test
public void testIopCallsProtectedAccessMethod(){
compile("access/JavaAccessModifiers.java");
assertErrors("access/CallsProtectedAccessMethod",
new CompilerError(23, "member method or attribute is not visible: protectedAccessMethod of type JavaAccessModifiers"));
}
@Test
@Ignore("#396")
public void testIopRefinesAndCallsProtectedAccessMethod(){
compile("access/JavaAccessModifiers.java");
compareWithJavaSource("access/RefinesAndCallsProtectedAccessMethod");
}
@Test
public void testIopRefinesDefaultAccessMethod(){
compile("access/JavaAccessModifiers.java");
// XXX This error comes from javac rather than the ceylon typechecker
assertErrors("access/RefinesDefaultAccessMethod",
new CompilerError(22, "defaultAccessMethod() in com.redhat.ceylon.compiler.java.test.interop.access.RefinesDefaultAccessMethod cannot override defaultAccessMethod() in com.redhat.ceylon.compiler.java.test.interop.access.JavaAccessModifiers; attempting to assign weaker access privileges; was package"));
}
@Test
public void testIopRefinesDefaultAccessMethodWithActual(){
compile("access/JavaAccessModifiers.java");
assertErrors("access/RefinesDefaultAccessMethodWithActual",
new CompilerError(22, "actual member does not refine any inherited member"),
new CompilerError(22, "actual member is not shared"));
}
@Test
public void testIopRefinesDefaultAccessMethodWithSharedActual(){
compile("access/JavaAccessModifiers.java");
assertErrors("access/RefinesDefaultAccessMethodWithSharedActual",
new CompilerError(22, "actual member does not refine any inherited member"));
}
@Test
public void testIopCallsDefaultAccessMethod(){
compile("access/JavaAccessModifiers.java");
assertErrors("access/CallsDefaultAccessMethod",
new CompilerError(23, "member method or attribute does not exist: packageAccessMethod in type JavaAccessModifiers"));
}
@Test
public void testIopExtendsDefaultAccessClass(){
compile("access/JavaAccessModifiers.java");
compareWithJavaSource("access/ExtendsDefaultAccessClass");
}
@Test
public void testIopExtendsDefaultAccessClassInAnotherPkg(){
compile("access/JavaAccessModifiers.java");
assertErrors("ExtendsDefaultAccessClassInAnotherPkg",
new CompilerError(20, "imported declaration is not shared: JavaDefaultAccessClass"),
new CompilerError(23, "com.redhat.ceylon.compiler.java.test.interop.access.JavaDefaultAccessClass is not public in com.redhat.ceylon.compiler.java.test.interop.access; cannot be accessed from outside package"));
}
@Test
public void testIopNamedInvocations(){
assertErrors("NamedInvocations",
+ new CompilerError(30, "could not determine type of method or attribute reference: createTempFile"),
new CompilerError(30, "named invocations of Java methods not supported"),
new CompilerError(32, "named invocations of Java methods not supported"),
new CompilerError(35, "named invocations of Java methods not supported"),
new CompilerError(37, "named invocations of Java methods not supported")
);
}
@Test
public void testIopOverrideStaticMethods(){
compile("JavaWithStaticMembers.java");
assertErrors("OverrideStaticMethods",
new CompilerError(26, "member refines a non-default, non-formal member"),
new CompilerError(28, "member refines a non-default, non-formal member")
);
}
}
| true | true | public void testIopNamedInvocations(){
assertErrors("NamedInvocations",
new CompilerError(30, "named invocations of Java methods not supported"),
new CompilerError(32, "named invocations of Java methods not supported"),
new CompilerError(35, "named invocations of Java methods not supported"),
new CompilerError(37, "named invocations of Java methods not supported")
);
}
| public void testIopNamedInvocations(){
assertErrors("NamedInvocations",
new CompilerError(30, "could not determine type of method or attribute reference: createTempFile"),
new CompilerError(30, "named invocations of Java methods not supported"),
new CompilerError(32, "named invocations of Java methods not supported"),
new CompilerError(35, "named invocations of Java methods not supported"),
new CompilerError(37, "named invocations of Java methods not supported")
);
}
|
diff --git a/src/Test.java b/src/Test.java
index d5c171a..42e9200 100644
--- a/src/Test.java
+++ b/src/Test.java
@@ -1,80 +1,80 @@
import java.lang.reflect.Method;
/**
*
* @author Englisch (e1125164), Lenz (e1126963), Schuster (e1025700)
* @since December 2012
*
*/
@Writer("Lena Lenz")
public class Test {
public static void main(String[] args) {
Bauernhof bauernhof = new Bauernhof("Mein Bauernhof");
TraktorList list = new TraktorList();
Dieseltraktor d1 = new Dieseltraktor();
Dieseltraktor d2 = new Dieseltraktor();
Dieseltraktor d3 = new Dieseltraktor();
Dieseltraktor d4 = new Dieseltraktor();
Biogastraktor b1 = new Biogastraktor();
Biogastraktor b2 = new Biogastraktor();
Biogastraktor b3 = new Biogastraktor();
d1.setBetriebsstunden(3);
d2.setBetriebsstunden(100);
d3.setBetriebsstunden(29);
d4.setBetriebsstunden(77);
b1.setBetriebsstunden(10);
b2.setBetriebsstunden(98);
b3.setBetriebsstunden(5);
d1.setEinsatzart(new Drillmaschine(100));
b1.setEinsatzart(new Duengerstreuer(100));
list.append(d1);
list.append(d2);
list.append(d3);
list.append(d4);
list.append(b1);
list.append(b2);
list.append(b3);
System.out.println(list);
System.out.println(list.find(b1).getData()); //find b1
- bauernhof.addTraktorenliste(list);
+ bauernhof.addTraktorList(list);
System.out.println(bauernhof.avgBetriebsstundenArt());
System.out.println(bauernhof.avgBetriebsstundenEinsatz());
// Reflection Test
System.out.println("\n\nReflection Tests:");
System.out.print(getClassMethodWriters(Bauernhof.class));
System.out.print(getClassMethodWriters(Biogastraktor.class));
System.out.print(getClassMethodWriters(Dieseltraktor.class));
System.out.print(getClassMethodWriters(Drillmaschine.class));
System.out.print(getClassMethodWriters(Duengerstreuer.class));
System.out.print(getClassMethodWriters(Einsatzart.class));
System.out.print(getClassMethodWriters(LinkedList.class));
System.out.print(getClassMethodWriters(Node.class));
System.out.print(getClassMethodWriters(ObjectIterator.class));
System.out.print(getClassMethodWriters(Test.class));
System.out.print(getClassMethodWriters(Traktor.class));
System.out.print(getClassMethodWriters(Writer.class));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Writer("Jakob Englisch")
public static String getClassMethodWriters(Class c) {
String tmp = "";
if(c == null)
return tmp;
Writer cw = (Writer) c.getAnnotation(Writer.class);
tmp += c.getName() + " wurde geschrieben von: " + (cw == null ? "keine Informationen vorhanden" : cw.value()) + "\n";
for(Method m : c.getMethods()) {
Writer cm = (Writer) m.getAnnotation(Writer.class);
if(cm == null)
continue;
tmp += c.getName() + ": "+ m.getName() + " wurde geschrieben von: " + cm.value() + "\n";
}
return tmp;
}
}
| true | true | public static void main(String[] args) {
Bauernhof bauernhof = new Bauernhof("Mein Bauernhof");
TraktorList list = new TraktorList();
Dieseltraktor d1 = new Dieseltraktor();
Dieseltraktor d2 = new Dieseltraktor();
Dieseltraktor d3 = new Dieseltraktor();
Dieseltraktor d4 = new Dieseltraktor();
Biogastraktor b1 = new Biogastraktor();
Biogastraktor b2 = new Biogastraktor();
Biogastraktor b3 = new Biogastraktor();
d1.setBetriebsstunden(3);
d2.setBetriebsstunden(100);
d3.setBetriebsstunden(29);
d4.setBetriebsstunden(77);
b1.setBetriebsstunden(10);
b2.setBetriebsstunden(98);
b3.setBetriebsstunden(5);
d1.setEinsatzart(new Drillmaschine(100));
b1.setEinsatzart(new Duengerstreuer(100));
list.append(d1);
list.append(d2);
list.append(d3);
list.append(d4);
list.append(b1);
list.append(b2);
list.append(b3);
System.out.println(list);
System.out.println(list.find(b1).getData()); //find b1
bauernhof.addTraktorenliste(list);
System.out.println(bauernhof.avgBetriebsstundenArt());
System.out.println(bauernhof.avgBetriebsstundenEinsatz());
// Reflection Test
System.out.println("\n\nReflection Tests:");
System.out.print(getClassMethodWriters(Bauernhof.class));
System.out.print(getClassMethodWriters(Biogastraktor.class));
System.out.print(getClassMethodWriters(Dieseltraktor.class));
System.out.print(getClassMethodWriters(Drillmaschine.class));
System.out.print(getClassMethodWriters(Duengerstreuer.class));
System.out.print(getClassMethodWriters(Einsatzart.class));
System.out.print(getClassMethodWriters(LinkedList.class));
System.out.print(getClassMethodWriters(Node.class));
System.out.print(getClassMethodWriters(ObjectIterator.class));
System.out.print(getClassMethodWriters(Test.class));
System.out.print(getClassMethodWriters(Traktor.class));
System.out.print(getClassMethodWriters(Writer.class));
}
| public static void main(String[] args) {
Bauernhof bauernhof = new Bauernhof("Mein Bauernhof");
TraktorList list = new TraktorList();
Dieseltraktor d1 = new Dieseltraktor();
Dieseltraktor d2 = new Dieseltraktor();
Dieseltraktor d3 = new Dieseltraktor();
Dieseltraktor d4 = new Dieseltraktor();
Biogastraktor b1 = new Biogastraktor();
Biogastraktor b2 = new Biogastraktor();
Biogastraktor b3 = new Biogastraktor();
d1.setBetriebsstunden(3);
d2.setBetriebsstunden(100);
d3.setBetriebsstunden(29);
d4.setBetriebsstunden(77);
b1.setBetriebsstunden(10);
b2.setBetriebsstunden(98);
b3.setBetriebsstunden(5);
d1.setEinsatzart(new Drillmaschine(100));
b1.setEinsatzart(new Duengerstreuer(100));
list.append(d1);
list.append(d2);
list.append(d3);
list.append(d4);
list.append(b1);
list.append(b2);
list.append(b3);
System.out.println(list);
System.out.println(list.find(b1).getData()); //find b1
bauernhof.addTraktorList(list);
System.out.println(bauernhof.avgBetriebsstundenArt());
System.out.println(bauernhof.avgBetriebsstundenEinsatz());
// Reflection Test
System.out.println("\n\nReflection Tests:");
System.out.print(getClassMethodWriters(Bauernhof.class));
System.out.print(getClassMethodWriters(Biogastraktor.class));
System.out.print(getClassMethodWriters(Dieseltraktor.class));
System.out.print(getClassMethodWriters(Drillmaschine.class));
System.out.print(getClassMethodWriters(Duengerstreuer.class));
System.out.print(getClassMethodWriters(Einsatzart.class));
System.out.print(getClassMethodWriters(LinkedList.class));
System.out.print(getClassMethodWriters(Node.class));
System.out.print(getClassMethodWriters(ObjectIterator.class));
System.out.print(getClassMethodWriters(Test.class));
System.out.print(getClassMethodWriters(Traktor.class));
System.out.print(getClassMethodWriters(Writer.class));
}
|
diff --git a/branches/java/jmonitor/src/jmonitor/MonitorApplet.java b/branches/java/jmonitor/src/jmonitor/MonitorApplet.java
index dd2d11a..df05d54 100644
--- a/branches/java/jmonitor/src/jmonitor/MonitorApplet.java
+++ b/branches/java/jmonitor/src/jmonitor/MonitorApplet.java
@@ -1,102 +1,102 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* MonitorApplet.java
*
* Created on 01-Feb-2010, 11:05:21
*/
package jmonitor;
import javax.swing.JFrame;
/**
*
* @author john
*/
public class MonitorApplet extends javax.swing.JApplet {
/** Initializes the applet MonitorApplet */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
monitorPanel = new jmonitor.MonitorPanel();
getContentPane().setLayout(null);
getContentPane().add(monitorPanel);
monitorPanel.setBounds(0, 0, 482, 230);
}// </editor-fold>//GEN-END:initComponents
public void start() {
// get the host we came from
String s=getCodeBase().getHost();
s=this.getParameter("server");
if(s!=null) {
server=s;
}
s=this.getParameter("receiver");
if(s!=null) {
receiver=Integer.parseInt(s);
}
audio = new Audio(server, receiver);
client = new Client(server, receiver,audio);
client.start();
client.setFrequency(7048000);
client.setMode(0);
client.setFilter(-2850, -150);
- client.setAGC(0);
+ client.setAGC(1);
client.setGain(30);
monitorPanel.setClient(client);
add(monitorPanel);
MonitorUpdateThread monitorUpdateThread = new MonitorUpdateThread(client, monitorPanel);
monitorUpdateThread.start();
}
public void stop() {
}
public void destroy() {
audio.close();
client.close();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private jmonitor.MonitorPanel monitorPanel;
// End of variables declaration//GEN-END:variables
String server = "81.146.61.118";
int receiver = 0;
Client client;
Audio audio;
}
| true | true | public void start() {
// get the host we came from
String s=getCodeBase().getHost();
s=this.getParameter("server");
if(s!=null) {
server=s;
}
s=this.getParameter("receiver");
if(s!=null) {
receiver=Integer.parseInt(s);
}
audio = new Audio(server, receiver);
client = new Client(server, receiver,audio);
client.start();
client.setFrequency(7048000);
client.setMode(0);
client.setFilter(-2850, -150);
client.setAGC(0);
client.setGain(30);
monitorPanel.setClient(client);
add(monitorPanel);
MonitorUpdateThread monitorUpdateThread = new MonitorUpdateThread(client, monitorPanel);
monitorUpdateThread.start();
}
| public void start() {
// get the host we came from
String s=getCodeBase().getHost();
s=this.getParameter("server");
if(s!=null) {
server=s;
}
s=this.getParameter("receiver");
if(s!=null) {
receiver=Integer.parseInt(s);
}
audio = new Audio(server, receiver);
client = new Client(server, receiver,audio);
client.start();
client.setFrequency(7048000);
client.setMode(0);
client.setFilter(-2850, -150);
client.setAGC(1);
client.setGain(30);
monitorPanel.setClient(client);
add(monitorPanel);
MonitorUpdateThread monitorUpdateThread = new MonitorUpdateThread(client, monitorPanel);
monitorUpdateThread.start();
}
|
diff --git a/src/com/eschers/eschermonitor/EscherMonitor.java b/src/com/eschers/eschermonitor/EscherMonitor.java
index 2197ceb..7ffb1b5 100644
--- a/src/com/eschers/eschermonitor/EscherMonitor.java
+++ b/src/com/eschers/eschermonitor/EscherMonitor.java
@@ -1,503 +1,503 @@
package com.eschers.eschermonitor;
import com.rapplogic.xbee.api.*;
import com.rapplogic.xbee.api.wpan.IoSample;
import com.rapplogic.xbee.api.wpan.RxResponseIoSample;
import org.w3c.dom.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
// import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import javax.xml.parsers.*;
import org.apache.log4j.*;
import com.google.gson.Gson;
public class EscherMonitor {
public enum storeType { FILE, WEB };
public static storeType store;
public static String storeURI = null;
public static int storeKey;
public static String configURI = null;
public static String controller = null;
public static String TEDURI = null;
public static File logFile = null;
public static boolean gotOneXbee = false;
public static int readInterval = 120; // Max read interval for sensors is 2 minutes
public static class xbeeCoordinatorConfig {
public String port;
public int speed;
public XBee xbee;
}
public static class sensorConfig {
public String id;
public String type;
public String name;
public int addressH;
public int addressL;
public float offset; // Offset for measurement conversion
public float scale; // Scale for offset conversion
public String interval; // Interval in second between measurements, ends with an "s" possibly.
public int intervalSec;
public XBeeAddress16 xbeeAddress;
public XBee xbee;
public sensorConfig makeSensor()
{
sensorConfig sensor = new sensorConfig();
sensor.id = this.id;
sensor.type = this.type;
sensor.name = this.name;
sensor.addressL = this.addressL;
sensor.addressH = this.addressH;
sensor.offset = this.offset;
sensor.scale = this.scale;
sensor.intervalSec = Integer.parseInt(this.interval.split("s")[0]);
return sensor;
}
}
public static class measurement { //ToDo: Change to "xbeeMeasurement"
public XBeeAddress16 xbeeAddress;
public int metric;
public Date ts;
public measurement(XBeeAddress16 addr, int met, Date t) {
xbeeAddress = addr;
metric = met;
ts = t;
}
}
private final static Logger logger = Logger.getLogger(EscherMonitor.class);
private final static int request_key(String cntrl) {
int check_hash = 0;
byte[] a = cntrl.getBytes();
for (int i=0; i < a.length; i++) {
check_hash += a[i] + 0;
}
check_hash *= storeKey;
check_hash %= 65536;
logger.debug("Hash: " + check_hash);
return check_hash;
}
public static Queue<measurement> measurements = new LinkedList<measurement>();
public static xbeeCoordinatorConfig xbeeCoordinator = null;
public static sensorConfig[] sensors = null;
private final static void fileData(sensorConfig sensor, int metric, Date ts) {
// For file storage...
FileWriter storeFile = null;
BufferedWriter storeOut = null;
// For web storage...
BufferedReader in = null;
DocumentBuilder responseBuilder = null;
URL url = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
if (store == storeType.FILE) {
try {
storeFile = new FileWriter(storeURI);
storeOut = new BufferedWriter(storeFile);
} catch (Exception e) {
logger.error("Counld not open file " + storeURI);
e.printStackTrace();
System.exit(1);
}
}
String output = new String();
if (store == storeType.FILE) {
output = sensor.id + "," + sensor.name + "," + (metric*sensor.scale + sensor.offset) + "," + ts.toString();
try {
logger.debug("Filing measurement: " + output);
storeOut.write(output);
storeOut.newLine();
} catch (IOException e) {
logger.warn("Could not write to output file: " + output );
}
}
if (store == storeType.WEB) {
try {
output = "/measurements?" + "sensor_id=" + URLEncoder.encode(sensor.id,"UTF-8") + "&" + "value=" + URLEncoder.encode("" + metric, "UTF-8") + "&" + "ts=" + URLEncoder.encode(formatter.format(ts), "UTF-8") + "&" + "key=" + request_key("" + metric);
logger.debug("Filing measurement: " + output);
url = new URL(storeURI + output);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "0");
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
connection.disconnect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String responseText = "";
while ((inputLine = in.readLine()) != null) responseText += inputLine;
in.close();
logger.debug("Response: " + responseText);
if (responseText.indexOf("Filed") > -1) {
logger.debug("Filed successfully.");
} else {
logger.warn("Filer error: " + responseText);
}
} catch (Exception e) {
logger.error("Could not file output: " + e.getMessage());
}
}
if (store == storeType.FILE) {
try {
storeOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
NodeList nl = null;
NodeList nl2 = null;
int i;
String configFile = "";
if (args.length > 0 ) {
configFile = args[0];
}
if (configFile == "") {
configFile = "config.xml";
}
PropertyConfigurator.configure("log4j.properties");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(configFile);
// Parse the main nodes
nl = doc.getElementsByTagName("storeMethod");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
if ((storeVal != null) && storeVal.matches("web")) {
store = storeType.WEB;
} else {
store = storeType.FILE;
}
}
logger.debug("Store type: " + store.toString());
nl = doc.getElementsByTagName("storeURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeURI = storeVal;
}
logger.debug("Store URI: " + storeURI);
nl = doc.getElementsByTagName("storeKey");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeKey = Integer.parseInt(storeVal);
}
logger.debug("Store Key: " + storeKey);
nl = doc.getElementsByTagName("configURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
configURI = storeVal;
}
logger.debug("Config URI: " + configURI);
nl = doc.getElementsByTagName("TEDURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
TEDURI = storeVal;
}
logger.debug("TED URI: " + TEDURI);
nl = doc.getElementsByTagName("controller");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
controller = storeVal;
}
logger.debug("Controller ID: " + controller);
// Parse the xbee coordinator
nl = doc.getElementsByTagName("xbeeCoordinator");
if ((nl.item(0) != null)) {
xbeeCoordinator = new xbeeCoordinatorConfig();
nl2 = nl.item(0).getChildNodes();
for (i=0; i < nl2.getLength(); i++)
{
if (nl2.item(i).getNodeName() == "port")
{
xbeeCoordinator.port = nl2.item(i).getTextContent();
}
if (nl2.item(i).getNodeName() == "speed")
{
xbeeCoordinator.speed = Integer.parseInt(nl2.item(i).getTextContent());
}
}
logger.debug("XBee Coordinator Port: " + xbeeCoordinator.port);
logger.debug("XBee Coordinator Speed: " + xbeeCoordinator.speed);
}
// nl = doc.getElementsByTagName("xbee");
// if ((nl != null) && (nl.getLength() > 0)) {
// xbees = new xbeeConfig[nl.getLength()];
// for (i=0; i < nl.getLength(); i++) {
// xbees[i] = new xbeeConfig();
// nl2 = nl.item(i).getChildNodes();
// for (j=0; j < nl2.getLength(); j++)
// {
// if (nl2.item(j).getNodeName() == "id")
// {
// xbees[i].id = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "name")
// {
// xbees[i].name = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "addressH")
// {
// xbees[i].addressH = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "addressL")
// {
// xbees[i].addressL = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "offset")
// {
// xbees[i].offset = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "scale")
// {
// xbees[i].scale = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "interval")
// {
// xbees[i].interval = Integer.parseInt(nl2.item(j).getTextContent(),10);
// }
// }
//
// //Defaults
// if (xbees[i].interval < 1) xbees[i].interval = 10000;
//
// logger.debug("XBee ID: " + xbees[i].id);
// logger.debug("XBee AddressH: " + xbees[i].addressH);
// logger.debug("XBee AddressL: " + xbees[i].addressL);
// logger.debug("XBee Interval: " + xbees[i].interval);
// }
// }
Gson gson = new Gson();
String configCommand = new String();
URL configURL = null;
BufferedReader configIn = null;
configCommand = "/sensors/getconfig?" + "cntrl=" + controller + "&key=" + request_key(controller);
logger.debug("Asking for config: " + configCommand);
configURL = new URL(configURI + configCommand);
configIn = new BufferedReader(new InputStreamReader(configURL.openStream()));
String inputLine;
String responseText = "";
while ((inputLine = configIn.readLine()) != null) responseText += inputLine;
configIn.close();
logger.debug("Response: " + responseText);
sensorConfig[] sensorsLoad = gson.fromJson(responseText, sensorConfig[].class); //ToDo++ change to generic sensor class. Get minimum interval for non-xbee sensors
sensors = new sensorConfig[sensorsLoad.length];
for (i=0; i<sensorsLoad.length; i++) {
//Defaults
sensors[i] = sensorsLoad[i].makeSensor();
if (sensors[i].intervalSec < 1) sensors[i].intervalSec = 120;
if ((sensors[i].type != "xbee temp") && (sensors[i].intervalSec < readInterval)) readInterval = sensors[i].intervalSec;
logger.debug("Sensor ID:" + sensors[i].id);
logger.debug("Sensor Type:" + sensors[i].type);
logger.debug("Sensor AddressL: " + sensors[i].addressL);
logger.debug("Sensor AddressH: " + sensors[i].addressH);
logger.debug("Sensor Interval: " + sensors[i].intervalSec);
}
}
catch (Exception e) {
// e.printStackTrace();
e.getMessage();
}
// Create our coordinator Xbee and try to talk to it
xbeeCoordinator.xbee = new XBee();
try {
xbeeCoordinator.xbee.open(xbeeCoordinator.port, xbeeCoordinator.speed);
} catch (XBeeException e) {
logger.error("Could not initialize Xbee coordinator.");
e.printStackTrace();
System.exit(1);
}
AtCommand at = new AtCommand("CH");
AtCommandResponse response = null;
try {
response = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(at, 5*1000);
} catch (XBeeTimeoutException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - timeout.");
e.printStackTrace();
System.exit(1);
} catch (XBeeException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
if (response.isOk()) {
// success
logger.debug("The local channel is " + response.getValue()[0]);
} else {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator.");
System.exit(1);
}
// Create our Xbees and try to communicate with them ToDo: Only do for "xbee" type sensors
AtCommandResponse rresponse = null;
for (i=0; i < sensors.length; i++) {
logger.debug("Looking at sensor " + i + ": id=" + sensors[i].id + " type=" + sensors[i].type);
if (sensors[i].type.equals("xbee temp")) {
sensors[i].xbee = new XBee();
sensors[i].xbeeAddress = new XBeeAddress16(sensors[i].addressH, sensors[i].addressL);
RemoteAtRequest rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, false, "CH");
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate (timeout) with Xbee id: " + sensors[i].id);
continue;
} catch (XBeeException e) {
logger.warn("Could not initialize Xbee id: " + sensors[i].id);
e.printStackTrace();
continue;
}
// if (rresponse.isOk()) {
// success, set up listener
logger.debug("Found Xbee id: " + sensors[i].id);
// set measurement interval
int[] intArr = new int[] {(int)(sensors[i].intervalSec*1000 >>> 8 & 0xff), (int)(sensors[i].intervalSec*1000 & 0xff)};
rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, true, "IR", intArr);
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate measurement interval to (timeout) Xbee id: " + sensors[i].id);
} catch (XBeeException e) {
logger.warn("Could not set measurement interval for Xbee id: " + sensors[i].id);
e.printStackTrace();
}
}
}
// Create a listener for the coordinator that puts entries on the queue
xbeeCoordinator.xbee.addPacketListener(new PacketListener() {
public void processResponse(XBeeResponse response) {
if (response.getApiId() == ApiId.RX_16_IO_RESPONSE || response.getApiId() == ApiId.RX_64_RESPONSE) {
RxResponseIoSample ioSample = (RxResponseIoSample)response;
logger.debug("Received a sample from " + ioSample.getSourceAddress());
logger.debug("RSSI is " + ioSample.getRssi());
XBeeAddress16 addr = new XBeeAddress16(ioSample.getSourceAddress().getAddress());
// loops IT times
for (IoSample sample: ioSample.getSamples()) {
logger.debug("Analog D0 (pin 20) 10-bit reading is " + sample.getAnalog0());
measurement ms = new measurement(addr, sample.getAnalog0(), new Date(new Date().getTime()));
measurements.add(ms);
}
}
}
});
// Create a filer loop that stores queue entries to the storage file/database (what about offsets and scale factors?)
sensorConfig xbeeFound = null;
while (true) { //ToDo: create a reader loop for T5000 sensor
while (!measurements.isEmpty()) {
measurement ms = measurements.remove();
// Find the Xbee this came from
boolean found = false;
for (i=0; i<sensors.length & !found; i++) {
if (sensors[i].type.equals("xbee temp")) {
if (ms.xbeeAddress.equals(sensors[i].xbeeAddress)) {
found = true;
xbeeFound = sensors[i];
}
}
}
if (!found) {
logger.warn("Xbee not found for measurement with address " + ms.xbeeAddress.get16BitValue());
} else {
fileData(xbeeFound, ms.metric, ms.ts);
}
}
for (i=0;i < sensors.length; i++) {
if (sensors[i].type.equals("TED5000")) {
try {
URL TEDURL = new URL(TEDURI + "?INDEX=1&COUNT=1&MTU=" + sensors[i].addressH);
// BufferedReader TEDIn = new BufferedReader(new InputStreamReader(TEDURL.openStream()));
// String inputLine;
// String responseText = "";
// while ((inputLine = TEDIn.readLine()) != null) responseText += inputLine;
// TEDIn.close();
// logger.debug("TED Data: " + responseText);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(TEDURL.openStream());
// Parse the main nodes
int power = Integer.parseInt(doc.getElementsByTagName("POWER").item(0).getTextContent());
Date ts = new SimpleDateFormat("MM/dd/yyyy k:mm:ss").parse(doc.getElementsByTagName("DATE").item(0).getTextContent());
fileData(sensors[i], power, ts);
} catch (Exception e) {
if (e instanceof IOException) {
logger.debug("Error reading TED: " + e.getMessage()+ ": " + sensors[i].addressH);
- return;
+ // return;
} else {
e.printStackTrace();
}
}
}
}
try {
Thread.sleep(readInterval*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| true | true | public static void main(String[] args) {
NodeList nl = null;
NodeList nl2 = null;
int i;
String configFile = "";
if (args.length > 0 ) {
configFile = args[0];
}
if (configFile == "") {
configFile = "config.xml";
}
PropertyConfigurator.configure("log4j.properties");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(configFile);
// Parse the main nodes
nl = doc.getElementsByTagName("storeMethod");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
if ((storeVal != null) && storeVal.matches("web")) {
store = storeType.WEB;
} else {
store = storeType.FILE;
}
}
logger.debug("Store type: " + store.toString());
nl = doc.getElementsByTagName("storeURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeURI = storeVal;
}
logger.debug("Store URI: " + storeURI);
nl = doc.getElementsByTagName("storeKey");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeKey = Integer.parseInt(storeVal);
}
logger.debug("Store Key: " + storeKey);
nl = doc.getElementsByTagName("configURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
configURI = storeVal;
}
logger.debug("Config URI: " + configURI);
nl = doc.getElementsByTagName("TEDURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
TEDURI = storeVal;
}
logger.debug("TED URI: " + TEDURI);
nl = doc.getElementsByTagName("controller");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
controller = storeVal;
}
logger.debug("Controller ID: " + controller);
// Parse the xbee coordinator
nl = doc.getElementsByTagName("xbeeCoordinator");
if ((nl.item(0) != null)) {
xbeeCoordinator = new xbeeCoordinatorConfig();
nl2 = nl.item(0).getChildNodes();
for (i=0; i < nl2.getLength(); i++)
{
if (nl2.item(i).getNodeName() == "port")
{
xbeeCoordinator.port = nl2.item(i).getTextContent();
}
if (nl2.item(i).getNodeName() == "speed")
{
xbeeCoordinator.speed = Integer.parseInt(nl2.item(i).getTextContent());
}
}
logger.debug("XBee Coordinator Port: " + xbeeCoordinator.port);
logger.debug("XBee Coordinator Speed: " + xbeeCoordinator.speed);
}
// nl = doc.getElementsByTagName("xbee");
// if ((nl != null) && (nl.getLength() > 0)) {
// xbees = new xbeeConfig[nl.getLength()];
// for (i=0; i < nl.getLength(); i++) {
// xbees[i] = new xbeeConfig();
// nl2 = nl.item(i).getChildNodes();
// for (j=0; j < nl2.getLength(); j++)
// {
// if (nl2.item(j).getNodeName() == "id")
// {
// xbees[i].id = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "name")
// {
// xbees[i].name = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "addressH")
// {
// xbees[i].addressH = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "addressL")
// {
// xbees[i].addressL = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "offset")
// {
// xbees[i].offset = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "scale")
// {
// xbees[i].scale = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "interval")
// {
// xbees[i].interval = Integer.parseInt(nl2.item(j).getTextContent(),10);
// }
// }
//
// //Defaults
// if (xbees[i].interval < 1) xbees[i].interval = 10000;
//
// logger.debug("XBee ID: " + xbees[i].id);
// logger.debug("XBee AddressH: " + xbees[i].addressH);
// logger.debug("XBee AddressL: " + xbees[i].addressL);
// logger.debug("XBee Interval: " + xbees[i].interval);
// }
// }
Gson gson = new Gson();
String configCommand = new String();
URL configURL = null;
BufferedReader configIn = null;
configCommand = "/sensors/getconfig?" + "cntrl=" + controller + "&key=" + request_key(controller);
logger.debug("Asking for config: " + configCommand);
configURL = new URL(configURI + configCommand);
configIn = new BufferedReader(new InputStreamReader(configURL.openStream()));
String inputLine;
String responseText = "";
while ((inputLine = configIn.readLine()) != null) responseText += inputLine;
configIn.close();
logger.debug("Response: " + responseText);
sensorConfig[] sensorsLoad = gson.fromJson(responseText, sensorConfig[].class); //ToDo++ change to generic sensor class. Get minimum interval for non-xbee sensors
sensors = new sensorConfig[sensorsLoad.length];
for (i=0; i<sensorsLoad.length; i++) {
//Defaults
sensors[i] = sensorsLoad[i].makeSensor();
if (sensors[i].intervalSec < 1) sensors[i].intervalSec = 120;
if ((sensors[i].type != "xbee temp") && (sensors[i].intervalSec < readInterval)) readInterval = sensors[i].intervalSec;
logger.debug("Sensor ID:" + sensors[i].id);
logger.debug("Sensor Type:" + sensors[i].type);
logger.debug("Sensor AddressL: " + sensors[i].addressL);
logger.debug("Sensor AddressH: " + sensors[i].addressH);
logger.debug("Sensor Interval: " + sensors[i].intervalSec);
}
}
catch (Exception e) {
// e.printStackTrace();
e.getMessage();
}
// Create our coordinator Xbee and try to talk to it
xbeeCoordinator.xbee = new XBee();
try {
xbeeCoordinator.xbee.open(xbeeCoordinator.port, xbeeCoordinator.speed);
} catch (XBeeException e) {
logger.error("Could not initialize Xbee coordinator.");
e.printStackTrace();
System.exit(1);
}
AtCommand at = new AtCommand("CH");
AtCommandResponse response = null;
try {
response = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(at, 5*1000);
} catch (XBeeTimeoutException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - timeout.");
e.printStackTrace();
System.exit(1);
} catch (XBeeException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
if (response.isOk()) {
// success
logger.debug("The local channel is " + response.getValue()[0]);
} else {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator.");
System.exit(1);
}
// Create our Xbees and try to communicate with them ToDo: Only do for "xbee" type sensors
AtCommandResponse rresponse = null;
for (i=0; i < sensors.length; i++) {
logger.debug("Looking at sensor " + i + ": id=" + sensors[i].id + " type=" + sensors[i].type);
if (sensors[i].type.equals("xbee temp")) {
sensors[i].xbee = new XBee();
sensors[i].xbeeAddress = new XBeeAddress16(sensors[i].addressH, sensors[i].addressL);
RemoteAtRequest rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, false, "CH");
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate (timeout) with Xbee id: " + sensors[i].id);
continue;
} catch (XBeeException e) {
logger.warn("Could not initialize Xbee id: " + sensors[i].id);
e.printStackTrace();
continue;
}
// if (rresponse.isOk()) {
// success, set up listener
logger.debug("Found Xbee id: " + sensors[i].id);
// set measurement interval
int[] intArr = new int[] {(int)(sensors[i].intervalSec*1000 >>> 8 & 0xff), (int)(sensors[i].intervalSec*1000 & 0xff)};
rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, true, "IR", intArr);
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate measurement interval to (timeout) Xbee id: " + sensors[i].id);
} catch (XBeeException e) {
logger.warn("Could not set measurement interval for Xbee id: " + sensors[i].id);
e.printStackTrace();
}
}
}
// Create a listener for the coordinator that puts entries on the queue
xbeeCoordinator.xbee.addPacketListener(new PacketListener() {
public void processResponse(XBeeResponse response) {
if (response.getApiId() == ApiId.RX_16_IO_RESPONSE || response.getApiId() == ApiId.RX_64_RESPONSE) {
RxResponseIoSample ioSample = (RxResponseIoSample)response;
logger.debug("Received a sample from " + ioSample.getSourceAddress());
logger.debug("RSSI is " + ioSample.getRssi());
XBeeAddress16 addr = new XBeeAddress16(ioSample.getSourceAddress().getAddress());
// loops IT times
for (IoSample sample: ioSample.getSamples()) {
logger.debug("Analog D0 (pin 20) 10-bit reading is " + sample.getAnalog0());
measurement ms = new measurement(addr, sample.getAnalog0(), new Date(new Date().getTime()));
measurements.add(ms);
}
}
}
});
// Create a filer loop that stores queue entries to the storage file/database (what about offsets and scale factors?)
sensorConfig xbeeFound = null;
while (true) { //ToDo: create a reader loop for T5000 sensor
while (!measurements.isEmpty()) {
measurement ms = measurements.remove();
// Find the Xbee this came from
boolean found = false;
for (i=0; i<sensors.length & !found; i++) {
if (sensors[i].type.equals("xbee temp")) {
if (ms.xbeeAddress.equals(sensors[i].xbeeAddress)) {
found = true;
xbeeFound = sensors[i];
}
}
}
if (!found) {
logger.warn("Xbee not found for measurement with address " + ms.xbeeAddress.get16BitValue());
} else {
fileData(xbeeFound, ms.metric, ms.ts);
}
}
for (i=0;i < sensors.length; i++) {
if (sensors[i].type.equals("TED5000")) {
try {
URL TEDURL = new URL(TEDURI + "?INDEX=1&COUNT=1&MTU=" + sensors[i].addressH);
// BufferedReader TEDIn = new BufferedReader(new InputStreamReader(TEDURL.openStream()));
// String inputLine;
// String responseText = "";
// while ((inputLine = TEDIn.readLine()) != null) responseText += inputLine;
// TEDIn.close();
// logger.debug("TED Data: " + responseText);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(TEDURL.openStream());
// Parse the main nodes
int power = Integer.parseInt(doc.getElementsByTagName("POWER").item(0).getTextContent());
Date ts = new SimpleDateFormat("MM/dd/yyyy k:mm:ss").parse(doc.getElementsByTagName("DATE").item(0).getTextContent());
fileData(sensors[i], power, ts);
} catch (Exception e) {
if (e instanceof IOException) {
logger.debug("Error reading TED: " + e.getMessage()+ ": " + sensors[i].addressH);
return;
} else {
e.printStackTrace();
}
}
}
}
try {
Thread.sleep(readInterval*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
NodeList nl = null;
NodeList nl2 = null;
int i;
String configFile = "";
if (args.length > 0 ) {
configFile = args[0];
}
if (configFile == "") {
configFile = "config.xml";
}
PropertyConfigurator.configure("log4j.properties");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(configFile);
// Parse the main nodes
nl = doc.getElementsByTagName("storeMethod");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
if ((storeVal != null) && storeVal.matches("web")) {
store = storeType.WEB;
} else {
store = storeType.FILE;
}
}
logger.debug("Store type: " + store.toString());
nl = doc.getElementsByTagName("storeURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeURI = storeVal;
}
logger.debug("Store URI: " + storeURI);
nl = doc.getElementsByTagName("storeKey");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
storeKey = Integer.parseInt(storeVal);
}
logger.debug("Store Key: " + storeKey);
nl = doc.getElementsByTagName("configURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
configURI = storeVal;
}
logger.debug("Config URI: " + configURI);
nl = doc.getElementsByTagName("TEDURI");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
TEDURI = storeVal;
}
logger.debug("TED URI: " + TEDURI);
nl = doc.getElementsByTagName("controller");
if ((nl.item(0) != null)) {
String storeVal = nl.item(0).getTextContent();
controller = storeVal;
}
logger.debug("Controller ID: " + controller);
// Parse the xbee coordinator
nl = doc.getElementsByTagName("xbeeCoordinator");
if ((nl.item(0) != null)) {
xbeeCoordinator = new xbeeCoordinatorConfig();
nl2 = nl.item(0).getChildNodes();
for (i=0; i < nl2.getLength(); i++)
{
if (nl2.item(i).getNodeName() == "port")
{
xbeeCoordinator.port = nl2.item(i).getTextContent();
}
if (nl2.item(i).getNodeName() == "speed")
{
xbeeCoordinator.speed = Integer.parseInt(nl2.item(i).getTextContent());
}
}
logger.debug("XBee Coordinator Port: " + xbeeCoordinator.port);
logger.debug("XBee Coordinator Speed: " + xbeeCoordinator.speed);
}
// nl = doc.getElementsByTagName("xbee");
// if ((nl != null) && (nl.getLength() > 0)) {
// xbees = new xbeeConfig[nl.getLength()];
// for (i=0; i < nl.getLength(); i++) {
// xbees[i] = new xbeeConfig();
// nl2 = nl.item(i).getChildNodes();
// for (j=0; j < nl2.getLength(); j++)
// {
// if (nl2.item(j).getNodeName() == "id")
// {
// xbees[i].id = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "name")
// {
// xbees[i].name = nl2.item(j).getTextContent();
// }
// if (nl2.item(j).getNodeName() == "addressH")
// {
// xbees[i].addressH = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "addressL")
// {
// xbees[i].addressL = Integer.parseInt(nl2.item(j).getTextContent(),16);
// }
// if (nl2.item(j).getNodeName() == "offset")
// {
// xbees[i].offset = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "scale")
// {
// xbees[i].scale = Float.parseFloat(nl2.item(j).getTextContent());
// }
// if (nl2.item(j).getNodeName() == "interval")
// {
// xbees[i].interval = Integer.parseInt(nl2.item(j).getTextContent(),10);
// }
// }
//
// //Defaults
// if (xbees[i].interval < 1) xbees[i].interval = 10000;
//
// logger.debug("XBee ID: " + xbees[i].id);
// logger.debug("XBee AddressH: " + xbees[i].addressH);
// logger.debug("XBee AddressL: " + xbees[i].addressL);
// logger.debug("XBee Interval: " + xbees[i].interval);
// }
// }
Gson gson = new Gson();
String configCommand = new String();
URL configURL = null;
BufferedReader configIn = null;
configCommand = "/sensors/getconfig?" + "cntrl=" + controller + "&key=" + request_key(controller);
logger.debug("Asking for config: " + configCommand);
configURL = new URL(configURI + configCommand);
configIn = new BufferedReader(new InputStreamReader(configURL.openStream()));
String inputLine;
String responseText = "";
while ((inputLine = configIn.readLine()) != null) responseText += inputLine;
configIn.close();
logger.debug("Response: " + responseText);
sensorConfig[] sensorsLoad = gson.fromJson(responseText, sensorConfig[].class); //ToDo++ change to generic sensor class. Get minimum interval for non-xbee sensors
sensors = new sensorConfig[sensorsLoad.length];
for (i=0; i<sensorsLoad.length; i++) {
//Defaults
sensors[i] = sensorsLoad[i].makeSensor();
if (sensors[i].intervalSec < 1) sensors[i].intervalSec = 120;
if ((sensors[i].type != "xbee temp") && (sensors[i].intervalSec < readInterval)) readInterval = sensors[i].intervalSec;
logger.debug("Sensor ID:" + sensors[i].id);
logger.debug("Sensor Type:" + sensors[i].type);
logger.debug("Sensor AddressL: " + sensors[i].addressL);
logger.debug("Sensor AddressH: " + sensors[i].addressH);
logger.debug("Sensor Interval: " + sensors[i].intervalSec);
}
}
catch (Exception e) {
// e.printStackTrace();
e.getMessage();
}
// Create our coordinator Xbee and try to talk to it
xbeeCoordinator.xbee = new XBee();
try {
xbeeCoordinator.xbee.open(xbeeCoordinator.port, xbeeCoordinator.speed);
} catch (XBeeException e) {
logger.error("Could not initialize Xbee coordinator.");
e.printStackTrace();
System.exit(1);
}
AtCommand at = new AtCommand("CH");
AtCommandResponse response = null;
try {
response = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(at, 5*1000);
} catch (XBeeTimeoutException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - timeout.");
e.printStackTrace();
System.exit(1);
} catch (XBeeException e) {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator - " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
if (response.isOk()) {
// success
logger.debug("The local channel is " + response.getValue()[0]);
} else {
// Failure, so none of this will work...
logger.error("Could not communicate with coordinator.");
System.exit(1);
}
// Create our Xbees and try to communicate with them ToDo: Only do for "xbee" type sensors
AtCommandResponse rresponse = null;
for (i=0; i < sensors.length; i++) {
logger.debug("Looking at sensor " + i + ": id=" + sensors[i].id + " type=" + sensors[i].type);
if (sensors[i].type.equals("xbee temp")) {
sensors[i].xbee = new XBee();
sensors[i].xbeeAddress = new XBeeAddress16(sensors[i].addressH, sensors[i].addressL);
RemoteAtRequest rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, false, "CH");
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate (timeout) with Xbee id: " + sensors[i].id);
continue;
} catch (XBeeException e) {
logger.warn("Could not initialize Xbee id: " + sensors[i].id);
e.printStackTrace();
continue;
}
// if (rresponse.isOk()) {
// success, set up listener
logger.debug("Found Xbee id: " + sensors[i].id);
// set measurement interval
int[] intArr = new int[] {(int)(sensors[i].intervalSec*1000 >>> 8 & 0xff), (int)(sensors[i].intervalSec*1000 & 0xff)};
rat = new RemoteAtRequest(XBeeRequest.DEFAULT_FRAME_ID, XBeeAddress64.BROADCAST, sensors[i].xbeeAddress, true, "IR", intArr);
try {
rresponse = (AtCommandResponse) xbeeCoordinator.xbee.sendSynchronous(rat, 5*1000);
} catch (XBeeTimeoutException e) {
logger.warn("Could not communicate measurement interval to (timeout) Xbee id: " + sensors[i].id);
} catch (XBeeException e) {
logger.warn("Could not set measurement interval for Xbee id: " + sensors[i].id);
e.printStackTrace();
}
}
}
// Create a listener for the coordinator that puts entries on the queue
xbeeCoordinator.xbee.addPacketListener(new PacketListener() {
public void processResponse(XBeeResponse response) {
if (response.getApiId() == ApiId.RX_16_IO_RESPONSE || response.getApiId() == ApiId.RX_64_RESPONSE) {
RxResponseIoSample ioSample = (RxResponseIoSample)response;
logger.debug("Received a sample from " + ioSample.getSourceAddress());
logger.debug("RSSI is " + ioSample.getRssi());
XBeeAddress16 addr = new XBeeAddress16(ioSample.getSourceAddress().getAddress());
// loops IT times
for (IoSample sample: ioSample.getSamples()) {
logger.debug("Analog D0 (pin 20) 10-bit reading is " + sample.getAnalog0());
measurement ms = new measurement(addr, sample.getAnalog0(), new Date(new Date().getTime()));
measurements.add(ms);
}
}
}
});
// Create a filer loop that stores queue entries to the storage file/database (what about offsets and scale factors?)
sensorConfig xbeeFound = null;
while (true) { //ToDo: create a reader loop for T5000 sensor
while (!measurements.isEmpty()) {
measurement ms = measurements.remove();
// Find the Xbee this came from
boolean found = false;
for (i=0; i<sensors.length & !found; i++) {
if (sensors[i].type.equals("xbee temp")) {
if (ms.xbeeAddress.equals(sensors[i].xbeeAddress)) {
found = true;
xbeeFound = sensors[i];
}
}
}
if (!found) {
logger.warn("Xbee not found for measurement with address " + ms.xbeeAddress.get16BitValue());
} else {
fileData(xbeeFound, ms.metric, ms.ts);
}
}
for (i=0;i < sensors.length; i++) {
if (sensors[i].type.equals("TED5000")) {
try {
URL TEDURL = new URL(TEDURI + "?INDEX=1&COUNT=1&MTU=" + sensors[i].addressH);
// BufferedReader TEDIn = new BufferedReader(new InputStreamReader(TEDURL.openStream()));
// String inputLine;
// String responseText = "";
// while ((inputLine = TEDIn.readLine()) != null) responseText += inputLine;
// TEDIn.close();
// logger.debug("TED Data: " + responseText);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(TEDURL.openStream());
// Parse the main nodes
int power = Integer.parseInt(doc.getElementsByTagName("POWER").item(0).getTextContent());
Date ts = new SimpleDateFormat("MM/dd/yyyy k:mm:ss").parse(doc.getElementsByTagName("DATE").item(0).getTextContent());
fileData(sensors[i], power, ts);
} catch (Exception e) {
if (e instanceof IOException) {
logger.debug("Error reading TED: " + e.getMessage()+ ": " + sensors[i].addressH);
// return;
} else {
e.printStackTrace();
}
}
}
}
try {
Thread.sleep(readInterval*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
index 154f0068d..2bcd34ef9 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
@@ -1,1241 +1,1249 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl.osm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opentripplanner.common.StreetUtils;
import org.opentripplanner.common.TurnRestriction;
import org.opentripplanner.common.TurnRestrictionType;
import org.opentripplanner.common.geometry.DistanceLibrary;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.common.model.P2;
import org.opentripplanner.graph_builder.impl.extra_elevation_data.ElevationPoint;
import org.opentripplanner.graph_builder.impl.extra_elevation_data.ExtraElevationData;
import org.opentripplanner.openstreetmap.model.OSMLevel;
import org.opentripplanner.openstreetmap.model.OSMLevel.Source;
import org.opentripplanner.openstreetmap.model.OSMNode;
import org.opentripplanner.openstreetmap.model.OSMRelation;
import org.opentripplanner.openstreetmap.model.OSMRelationMember;
import org.opentripplanner.openstreetmap.model.OSMTag;
import org.opentripplanner.openstreetmap.model.OSMWay;
import org.opentripplanner.openstreetmap.model.OSMWithTags;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.graph_builder.services.osm.CustomNamer;
import org.opentripplanner.openstreetmap.services.OpenStreetMapContentHandler;
import org.opentripplanner.openstreetmap.services.OpenStreetMapProvider;
import org.opentripplanner.routing.core.GraphBuilderAnnotation;
import org.opentripplanner.routing.core.GraphBuilderAnnotation.Variety;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.edgetype.EdgeWithElevation;
import org.opentripplanner.routing.edgetype.ElevatorAlightEdge;
import org.opentripplanner.routing.edgetype.ElevatorBoardEdge;
import org.opentripplanner.routing.edgetype.ElevatorHopEdge;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.PlainStreetEdge;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.patch.Alert;
import org.opentripplanner.routing.patch.TranslatedString;
import org.opentripplanner.routing.vertextype.ElevatorOffboardVertex;
import org.opentripplanner.routing.vertextype.ElevatorOnboardVertex;
import org.opentripplanner.routing.vertextype.IntersectionVertex;
import org.opentripplanner.util.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
/**
* Builds a street graph from OpenStreetMap data.
*
*/
public class OpenStreetMapGraphBuilderImpl implements GraphBuilder {
private static Logger _log = LoggerFactory.getLogger(OpenStreetMapGraphBuilderImpl.class);
private List<OpenStreetMapProvider> _providers = new ArrayList<OpenStreetMapProvider>();
private Map<Object, Object> _uniques = new HashMap<Object, Object>();
private WayPropertySet wayPropertySet = new WayPropertySet();
private CustomNamer customNamer;
private ExtraElevationData extraElevationData = new ExtraElevationData();
private boolean noZeroLevels = true;
/**
* The source for OSM map data
*/
public void setProvider(OpenStreetMapProvider provider) {
_providers.add(provider);
}
/**
* Multiple sources for OSM map data
*/
public void setProviders(List<OpenStreetMapProvider> providers) {
_providers.addAll(providers);
}
/**
* Set the way properties from a {@link WayPropertySetSource} source.
*
* @param source the way properties source
*/
public void setDefaultWayPropertySetSource(WayPropertySetSource source) {
wayPropertySet = source.getWayPropertySet();
}
/**
* If true, disallow zero floors and add 1 to non-negative numeric floors, as is generally done
* in the United States. This does not affect floor names from level maps. Default: true.
*/
public void setNoZeroLevels(boolean nz) {
noZeroLevels = nz;
}
@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
Handler handler = new Handler();
for (OpenStreetMapProvider provider : _providers) {
_log.debug("gathering osm from provider: " + provider);
provider.readOSM(handler);
}
_log.debug("building osm street graph");
handler.buildGraph(graph, extra);
}
@SuppressWarnings("unchecked")
private <T> T unique(T value) {
Object v = _uniques.get(value);
if (v == null) {
_uniques.put(value, value);
v = value;
}
return (T) v;
}
public void setWayPropertySet(WayPropertySet wayDataSet) {
this.wayPropertySet = wayDataSet;
}
public WayPropertySet getWayPropertySet() {
return wayPropertySet;
}
private class Handler implements OpenStreetMapContentHandler {
private Map<Long, OSMNode> _nodes = new HashMap<Long, OSMNode>();
private Map<Long, OSMWay> _ways = new HashMap<Long, OSMWay>();
private Map<Long, OSMRelation> _relations = new HashMap<Long, OSMRelation>();
private Set<Long> _nodesWithNeighbors = new HashSet<Long>();
private Map<Long, List<TurnRestrictionTag>> turnRestrictionsByFromWay =
new HashMap<Long, List<TurnRestrictionTag>>();
private Map<Long, List<TurnRestrictionTag>> turnRestrictionsByToWay =
new HashMap<Long, List<TurnRestrictionTag>>();
private Map<TurnRestrictionTag, TurnRestriction> turnRestrictionsByTag =
new HashMap<TurnRestrictionTag, TurnRestriction>();
private Graph graph;
/** The bike safety factor of the safest street */
private double bestBikeSafety = 1;
// track OSM nodes which are decomposed into multiple graph vertices because they are
// elevators. later they will be iterated over to build ElevatorEdges between them.
private HashMap<Long, HashMap<OSMLevel, IntersectionVertex>> multiLevelNodes =
new HashMap<Long, HashMap<OSMLevel, IntersectionVertex>>();
// track OSM nodes that will become graph vertices because they appear in multiple OSM ways
private Map<Long, IntersectionVertex> intersectionNodes =
new HashMap<Long, IntersectionVertex>();
// track vertices to be removed in the turn-graph conversion.
// this is a superset of intersectionNodes.values, which contains
// a null vertex reference for multilevel nodes. the individual vertices
// for each level of a multilevel node are includeed in endpoints.
private ArrayList<IntersectionVertex> endpoints = new ArrayList<IntersectionVertex>();
// track which vertical level each OSM way belongs to, for building elevators etc.
private Map<OSMWay, OSMLevel> wayLevels = new HashMap<OSMWay, OSMLevel>();
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
this.graph = graph;
// handle turn restrictions, road names, and level maps in relations
processRelations();
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
initIntersectionNodes();
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
for (OSMWay way : _ways.values()) {
if (wayIndex % 10000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
if (!way.hasTag("name")) {
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
}
Set<Alert> note = wayPropertySet.getNoteForWay(way);
Set<Alert> wheelchairNote = getWheelchairNotes(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way,
wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
IntersectionVertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
getLevelsForWay(way);
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry and
* ele tags. For nodes which are shared, create endpoints and StreetVertex
* instances.
*/
Long startNode = null;
//where the current edge should start
OSMNode osmStartNode = null;
List<ElevationPoint> elevationPoints = new ArrayList<ElevationPoint>();
double distance = 0;
for (int i = 0; i < nodes.size() - 1; i++) {
OSMNode segmentStartOSMNode = _nodes.get(nodes.get(i));
if (segmentStartOSMNode == null) {
continue;
}
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = segmentStartOSMNode;
elevationPoints.clear();
}
//where the current edge might end
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
String ele = segmentStartOSMNode.getTag("ele");
if (ele != null) {
- elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele)));
+ ele = ele.toLowerCase();
+ double unit = 1;
+ if (ele.endsWith("m")) {
+ ele = ele.replaceFirst("\\s*m", "");
+ } else if (ele.endsWith("ft")) {
+ ele = ele.replaceFirst("\\s*ft", "");
+ unit = 0.3048;
+ }
+ elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele) * unit));
}
distance += DistanceLibrary.distance(segmentStartOSMNode.getLat(), segmentStartOSMNode.getLon(),
osmEndNode.getLat(), osmEndNode.getLon());
if (intersectionNodes.containsKey(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
ele = osmEndNode.getTag("ele");
if (ele != null) {
elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele)));
}
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) { // first iteration on this way
// make or get a shared vertex for flat intersections,
// one vertex per level for multilevel nodes like elevators
startEndpoint = getVertexForOsmNode(osmStartNode, way);
} else { // subsequent iterations
startEndpoint = endEndpoint;
}
endEndpoint = getVertexForOsmNode(osmEndNode, way);
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety);
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
if (note != null) {
street.setNote(note);
}
if (wheelchairNote != null) {
street.setWheelchairNote(wheelchairNote);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
double safety = wayData.getSafetyFeatures().getSecond();
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety);
if (note != null) {
backStreet.setNote(note);
}
if (wheelchairNote != null) {
backStreet.setWheelchairNote(wheelchairNote);
}
}
storeExtraElevationData(elevationPoints, street, backStreet, distance);
applyEdgesToTurnRestrictions(way, startNode, endNode, street, backStreet);
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
} // END loop over OSM ways
buildElevatorEdges(graph);
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
if (customNamer != null) {
customNamer.postprocess(graph);
}
//generate elevation profiles
Map<EdgeWithElevation, List<ElevationPoint>> data = extraElevationData.data;
for (Map.Entry<EdgeWithElevation, List<ElevationPoint>> entry : data.entrySet()) {
EdgeWithElevation edge = entry.getKey();
List<ElevationPoint> points = entry.getValue();
Collections.sort(points);
if (points.size() == 1) {
ElevationPoint firstPoint = points.get(0);
ElevationPoint endPoint = new ElevationPoint(edge.getDistance(), firstPoint.ele);
points.add(endPoint);
}
Coordinate[] coords = new Coordinate[points.size()];
int i = 0;
for (ElevationPoint p : points) {
double d = p.distanceAlongShape;
if (i == 0) {
d = 0;
} else if (i == points.size() - 1) {
d = edge.getDistance();
}
coords[i++] = new Coordinate(d, p.ele);
}
edge.setElevationProfile(new PackedCoordinateSequence.Double(coords), true);
}
applyBikeSafetyFactor(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
} // END buildGraph()
private void storeExtraElevationData(List<ElevationPoint> elevationPoints, PlainStreetEdge street, PlainStreetEdge backStreet, double length) {
if (elevationPoints.isEmpty()) {
return;
}
for (ElevationPoint p : elevationPoints) {
MapUtils.addToMapList(extraElevationData.data, street, p);
MapUtils.addToMapList(extraElevationData.data, backStreet, p.fromBack(length));
}
}
private void buildElevatorEdges(Graph graph) {
/* build elevator edges */
for (Long nodeId : multiLevelNodes.keySet()) {
OSMNode node = _nodes.get(nodeId);
// this allows skipping levels, e.g., an elevator that stops
// at floor 0, 2, 3, and 5.
// Converting to an Array allows us to
// subscript it so we can loop over it in twos. Assumedly, it will stay
// sorted when we convert it to an Array.
// The objects are Integers, but toArray returns Object[]
HashMap<OSMLevel, IntersectionVertex> vertices = multiLevelNodes.get(nodeId);
/*
* first, build FreeEdges to disconnect from the graph, GenericVertices to serve as
* attachment points, and ElevatorBoard and ElevatorAlight edges to connect future
* ElevatorHop edges to. After this iteration, graph will look like (side view):
* +==+~~X
*
* +==+~~X
*
* +==+~~X
*
* + GenericVertex, X EndpointVertex, ~~ FreeEdge, ==
* ElevatorBoardEdge/ElevatorAlightEdge Another loop will fill in the
* ElevatorHopEdges.
*/
OSMLevel[] levels = vertices.keySet().toArray(new OSMLevel[0]);
Arrays.sort(levels);
ArrayList<Vertex> onboardVertices = new ArrayList<Vertex>();
for (OSMLevel level : levels) {
// get the node to build the elevator out from
IntersectionVertex sourceVertex = vertices.get(level);
String sourceVertexLabel = sourceVertex.getLabel();
String levelName = level.longName;
ElevatorOffboardVertex offboardVertex = new ElevatorOffboardVertex(graph,
sourceVertexLabel + "_offboard", sourceVertex.getX(),
sourceVertex.getY(), levelName);
new FreeEdge(sourceVertex, offboardVertex);
new FreeEdge(offboardVertex, sourceVertex);
ElevatorOnboardVertex onboardVertex = new ElevatorOnboardVertex(graph,
sourceVertexLabel + "_onboard", sourceVertex.getX(),
sourceVertex.getY(), levelName);
new ElevatorBoardEdge(offboardVertex, onboardVertex);
new ElevatorAlightEdge(onboardVertex, offboardVertex, level.longName);
// accumulate onboard vertices to so they can be connected by hop edges later
onboardVertices.add(onboardVertex);
}
// -1 because we loop over onboardVertices two at a time
for (Integer i = 0, vSize = onboardVertices.size() - 1; i < vSize; i++) {
Vertex from = onboardVertices.get(i);
Vertex to = onboardVertices.get(i + 1);
// default permissions: pedestrian, wheelchair, and bicycle
boolean wheelchairAccessible = true;
StreetTraversalPermission permission = StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE;
// check for bicycle=no, otherwise assume it's OK to take a bike
if (node.isTagFalse("bicycle")) {
permission = StreetTraversalPermission.PEDESTRIAN;
}
// check for wheelchair=no
if (node.isTagFalse("wheelchair")) {
wheelchairAccessible = false;
}
// The narrative won't be strictly correct, as it will show the elevator as part
// of the cycling leg, but I think most cyclists will figure out that they
// should really dismount.
ElevatorHopEdge foreEdge = new ElevatorHopEdge(from, to, permission);
ElevatorHopEdge backEdge = new ElevatorHopEdge(to, from, permission);
foreEdge.wheelchairAccessible = wheelchairAccessible;
backEdge.wheelchairAccessible = wheelchairAccessible;
}
} // END elevator edge loop
}
private void applyEdgesToTurnRestrictions(OSMWay way, long startNode, long endNode,
PlainStreetEdge street, PlainStreetEdge backStreet) {
/* Check if there are turn restrictions starting on this segment */
List<TurnRestrictionTag> restrictionTags = turnRestrictionsByFromWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = backStreet;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.from = street;
}
}
}
restrictionTags = turnRestrictionsByToWay.get(way.getId());
if (restrictionTags != null) {
for (TurnRestrictionTag tag : restrictionTags) {
if (tag.via == startNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = street;
} else if (tag.via == endNode) {
TurnRestriction restriction = turnRestrictionsByTag.get(tag);
restriction.to = backStreet;
}
}
}
}
private void getLevelsForWay(OSMWay way) {
/* Determine OSM level for each way, if it was not already set */
if (!wayLevels.containsKey(way)) {
// if this way is not a key in the wayLevels map, a level map was not
// already applied in processRelations
/* try to find a level name in tags */
String levelName = null;
OSMLevel.Source source = OSMLevel.Source.NONE;
OSMLevel level = OSMLevel.DEFAULT;
if (way.hasTag("level")) { // TODO: floating-point levels &c.
levelName = way.getTag("level");
source = OSMLevel.Source.LEVEL_TAG;
} else if (way.hasTag("layer")) {
levelName = way.getTag("layer");
source = OSMLevel.Source.LAYER_TAG;
}
if (levelName != null) {
level = OSMLevel.fromString(levelName, source, noZeroLevels);
}
wayLevels.put(way, level);
}
}
private void initIntersectionNodes() {
Set<Long> possibleIntersectionNodes = new HashSet<Long>();
for (OSMWay way : _ways.values()) {
List<Long> nodes = way.getNodeRefs();
for (long node : nodes) {
if (possibleIntersectionNodes.contains(node)) {
intersectionNodes.put(node, null);
} else {
possibleIntersectionNodes.add(node);
}
}
}
}
private Set<Alert> getWheelchairNotes(OSMWithTags way) {
Map<String, String> tags = way.getTagsByPrefix("wheelchair:description");
if (tags == null) {
return null;
}
Set<Alert> alerts = new HashSet<Alert>();
Alert alert = new Alert();
alerts.add(alert);
for (Map.Entry<String, String> entry : tags.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (k.equals("wheelchair:description")) {
// no language, assume default from TranslatedString
alert.alertHeaderText = new TranslatedString(v);
} else {
String lang = k.substring("wheelchair:description:".length());
alert.alertHeaderText = new TranslatedString(lang, v);
}
}
return alerts;
}
/**
* The safest bike lane should have a safety weight no lower than the time weight of a flat
* street. This method divides the safety lengths by the length ratio of the safest street,
* ensuring this property.
*
* @param graph
*/
private void applyBikeSafetyFactor(Graph graph) {
_log.info(GraphBuilderAnnotation.register(graph, Variety.GRAPHWIDE,
"Multiplying all bike safety values by " + (1 / bestBikeSafety)));
HashSet<Edge> seenEdges = new HashSet<Edge>();
for (Vertex vertex : graph.getVertices()) {
for (Edge e : vertex.getOutgoing()) {
if (!(e instanceof PlainStreetEdge)) {
continue;
}
PlainStreetEdge pse = (PlainStreetEdge) e;
if (!seenEdges.contains(e)) {
seenEdges.add(e);
pse.setBicycleSafetyEffectiveLength(pse.getBicycleSafetyEffectiveLength()
/ bestBikeSafety);
}
}
for (Edge e : vertex.getIncoming()) {
if (!(e instanceof PlainStreetEdge)) {
continue;
}
PlainStreetEdge pse = (PlainStreetEdge) e;
if (!seenEdges.contains(e)) {
seenEdges.add(e);
pse.setBicycleSafetyEffectiveLength(pse.getBicycleSafetyEffectiveLength()
/ bestBikeSafety);
}
}
}
}
private Coordinate getCoordinate(OSMNode osmNode) {
return new Coordinate(osmNode.getLon(), osmNode.getLat());
}
public void addNode(OSMNode node) {
if (!_nodesWithNeighbors.contains(node.getId()))
return;
if (_nodes.containsKey(node.getId()))
return;
_nodes.put(node.getId(), node);
if (_nodes.size() % 100000 == 0)
_log.debug("nodes=" + _nodes.size());
}
public void addWay(OSMWay way) {
if (_ways.containsKey(way.getId()))
return;
_ways.put(way.getId(), way);
if (_ways.size() % 10000 == 0)
_log.debug("ways=" + _ways.size());
}
public void addRelation(OSMRelation relation) {
if (_relations.containsKey(relation.getId()))
return;
if (!(relation.isTag("type", "restriction"))
&& !(relation.isTag("type", "route") && relation.isTag("route", "road"))
&& !(relation.isTag("type", "multipolygon") && relation.hasTag("highway"))
&& !(relation.isTag("type", "level_map"))) {
return;
}
_relations.put(relation.getId(), relation);
if (_relations.size() % 100 == 0)
_log.debug("relations=" + _relations.size());
}
public void secondPhase() {
int count = _ways.values().size();
// This copies relevant tags to the ways (highway=*) where it doesn't exist, so that
// the way purging keeps the needed way around.
// Multipolygons may be processed more than once, which may be needed since
// some member might be in different files for the same multipolygon.
processMultipolygons();
for (Iterator<OSMWay> it = _ways.values().iterator(); it.hasNext();) {
OSMWay way = it.next();
if (!(way.hasTag("highway") || way.isTag("railway", "platform"))) {
it.remove();
} else if (way.isTag("highway", "conveyer") || way.isTag("highway", "proposed")) {
it.remove();
} else if (way.isTag("area", "yes")) {
// routing on areas is not yet supported. areas can cause problems with stop linking.
// (24th & Mission BART plaza is both highway=pedestrian and area=yes)
it.remove();
} else {
// Since the way is kept, update nodes-with-neighbors
List<Long> nodes = way.getNodeRefs();
if (nodes.size() > 1) {
_nodesWithNeighbors.addAll(nodes);
}
}
}
_log.trace("purged " + (count - _ways.values().size()) + " ways out of " + count);
}
/**
* Copies useful metadata from multipolygon relations to the relevant ways.
*
* This is done at a different time than processRelations(), so that way purging doesn't
* remove the used ways.
*/
private void processMultipolygons() {
for (OSMRelation relation : _relations.values()) {
if (!(relation.isTag("type", "multipolygon") && relation.hasTag("highway"))) {
continue;
}
for (OSMRelationMember member : relation.getMembers()) {
if (!("way".equals(member.getType()) && _ways.containsKey(member.getRef()))) {
continue;
}
OSMWithTags way = _ways.get(member.getRef());
if (way == null) {
continue;
}
if (relation.hasTag("highway") && !way.hasTag("highway")) {
way.addTag("highway", relation.getTag("highway"));
}
if (relation.hasTag("name") && !way.hasTag("name")) {
way.addTag("name", relation.getTag("name"));
}
if (relation.hasTag("ref") && !way.hasTag("ref")) {
way.addTag("ref", relation.getTag("ref"));
}
}
}
}
/**
* Copies useful metadata from relations to the relevant ways/nodes.
*/
private void processRelations() {
_log.debug("Processing relations...");
for (OSMRelation relation : _relations.values()) {
if (relation.isTag("type", "restriction")) {
processRestriction(relation);
} else if (relation.isTag("type", "level_map")) {
processLevelMap(relation);
} else if (relation.isTag("type", "route")) {
processRoad(relation);
}
// multipolygons were already processed in secondPhase()
}
}
/**
* A temporary holder for turn restrictions while we have only way/node ids but not yet edge
* objects
*/
class TurnRestrictionTag {
private long via;
private TurnRestrictionType type;
TurnRestrictionTag(long via, TurnRestrictionType type) {
this.via = via;
this.type = type;
}
}
/**
* Handle turn restrictions
*
* @param relation
*/
private void processRestriction(OSMRelation relation) {
long from = -1, to = -1, via = -1;
for (OSMRelationMember member : relation.getMembers()) {
String role = member.getRole();
if (role.equals("from")) {
from = member.getRef();
} else if (role.equals("to")) {
to = member.getRef();
} else if (role.equals("via")) {
via = member.getRef();
}
}
if (from == -1 || to == -1 || via == -1) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TURN_RESTRICTION_BAD,
relation.getId()));
return;
}
Set<TraverseMode> modes = EnumSet.of(TraverseMode.BICYCLE, TraverseMode.CAR);
String exceptModes = relation.getTag("except");
if (exceptModes != null) {
for (String m : exceptModes.split(";")) {
if (m.equals("motorcar")) {
modes.remove(TraverseMode.CAR);
} else if (m.equals("bicycle")) {
modes.remove(TraverseMode.BICYCLE);
_log.warn(GraphBuilderAnnotation.register(graph,
Variety.TURN_RESTRICTION_EXCEPTION, via, from));
}
}
}
modes = TraverseMode.internSet(modes);
TurnRestrictionTag tag;
if (relation.isTag("restriction", "no_right_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_left_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_straight_on")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "no_u_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.NO_TURN);
} else if (relation.isTag("restriction", "only_straight_on")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else if (relation.isTag("restriction", "only_right_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else if (relation.isTag("restriction", "only_left_turn")) {
tag = new TurnRestrictionTag(via, TurnRestrictionType.ONLY_TURN);
} else {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.TURN_RESTRICTION_UNKNOWN,
relation.getTag("restriction")));
return;
}
TurnRestriction restriction = new TurnRestriction();
restriction.type = tag.type;
restriction.modes = modes;
turnRestrictionsByTag.put(tag, restriction);
MapUtils.addToMapList(turnRestrictionsByFromWay, from, tag);
MapUtils.addToMapList(turnRestrictionsByToWay, to, tag);
}
/**
* Process an OSM level map.
*
* @param relation
*/
private void processLevelMap(OSMRelation relation) {
Map<String, OSMLevel> levels = OSMLevel.mapFromSpecList(relation.getTag("levels"), Source.LEVEL_MAP, true);
for (OSMRelationMember member : relation.getMembers()) {
if ("way".equals(member.getType()) && _ways.containsKey(member.getRef())) {
OSMWay way = _ways.get(member.getRef());
if (way != null) {
String role = member.getRole();
// if the level map relation has a role:xyz tag, this way is something
// more complicated than a single level (e.g. ramp/stairway).
if (!relation.hasTag("role:" + role)) {
if (levels.containsKey(role)) {
wayLevels.put(way, levels.get(role));
} else {
_log.warn(member.getRef() + " has undefined level " + role);
}
}
}
}
}
}
/*
* Handle route=road relations.
*
* @param relation
*/
private void processRoad(OSMRelation relation) {
for (OSMRelationMember member : relation.getMembers()) {
if (!("way".equals(member.getType()) && _ways.containsKey(member.getRef()))) {
continue;
}
OSMWithTags way = _ways.get(member.getRef());
if (way == null) {
continue;
}
if (relation.hasTag("name")) {
if (way.hasTag("otp:route_name")) {
way.addTag(
"otp:route_name",
addUniqueName(way.getTag("otp:route_name"), relation.getTag("name")));
} else {
way.addTag(new OSMTag("otp:route_name", relation.getTag("name")));
}
}
if (relation.hasTag("ref")) {
if (way.hasTag("otp:route_ref")) {
way.addTag("otp:route_ref",
addUniqueName(way.getTag("otp:route_ref"), relation.getTag("ref")));
} else {
way.addTag(new OSMTag("otp:route_ref", relation.getTag("ref")));
}
}
}
}
private String addUniqueName(String routes, String name) {
String[] names = routes.split(", ");
for (String existing : names) {
if (existing.equals(name)) {
return routes;
}
}
return routes + ", " + name;
}
/**
* Handle oneway streets, cycleways, and whatnot. See
* http://wiki.openstreetmap.org/wiki/Bicycle for various scenarios, along with
* http://wiki.openstreetmap.org/wiki/OSM_tags_for_routing#Oneway.
*
* @param end
* @param start
*/
private P2<PlainStreetEdge> getEdgesForStreet(IntersectionVertex start,
IntersectionVertex end, OSMWithTags way, long startNode,
StreetTraversalPermission permissions, LineString geometry) {
// get geometry length in meters, irritatingly.
Coordinate[] coordinates = geometry.getCoordinates();
double d = 0;
for (int i = 1; i < coordinates.length; ++i) {
d += DistanceLibrary.distance(coordinates[i - 1], coordinates[i]);
}
LineString backGeometry = (LineString) geometry.reverse();
Map<String, String> tags = way.getTags();
if (permissions == StreetTraversalPermission.NONE)
return new P2<PlainStreetEdge>(null, null);
PlainStreetEdge street = null, backStreet = null;
/*
* pedestrian rules: everything is two-way (assuming pedestrians are allowed at all)
* bicycle rules: default: permissions;
*
* cycleway=dismount means walk your bike -- the engine will automatically try walking
* bikes any time it is forbidden to ride them, so the only thing to do here is to
* remove bike permissions
*
* oneway=... sets permissions for cars and bikes oneway:bicycle overwrites these
* permissions for bikes only
*
* now, cycleway=opposite_lane, opposite, opposite_track can allow once oneway has been
* set by oneway:bicycle, but should give a warning if it conflicts with oneway:bicycle
*
* bicycle:backward=yes works like oneway:bicycle=no bicycle:backwards=no works like
* oneway:bicycle=yes
*/
String foot = way.getTag("foot");
if ("yes".equals(foot) || "designated".equals(foot)) {
permissions = permissions.add(StreetTraversalPermission.PEDESTRIAN);
}
if (OSMWithTags.isFalse(foot)) {
permissions = permissions.remove(StreetTraversalPermission.PEDESTRIAN);
}
boolean forceBikes = false;
String bicycle = way.getTag("bicycle");
if ("yes".equals(bicycle) || "designated".equals(bicycle)) {
permissions = permissions.add(StreetTraversalPermission.BICYCLE);
forceBikes = true;
}
if (way.isTag("cycleway", "dismount") || "dismount".equals(bicycle)) {
permissions = permissions.remove(StreetTraversalPermission.BICYCLE);
if (forceBikes) {
_log.warn(GraphBuilderAnnotation.register(graph, Variety.CONFLICTING_BIKE_TAGS,
way.getId()));
}
}
StreetTraversalPermission permissionsFront = permissions;
StreetTraversalPermission permissionsBack = permissions;
if (way.isTagTrue("oneway") || "roundabout".equals(tags.get("junction"))) {
permissionsBack = permissionsBack.remove(StreetTraversalPermission.BICYCLE_AND_CAR);
}
if (way.isTag("oneway", "-1")) {
permissionsFront = permissionsFront
.remove(StreetTraversalPermission.BICYCLE_AND_CAR);
}
String oneWayBicycle = way.getTag("oneway:bicycle");
if (OSMWithTags.isTrue(oneWayBicycle) || way.isTagFalse("bicycle:backwards")) {
permissionsBack = permissionsBack.remove(StreetTraversalPermission.BICYCLE);
}
if ("-1".equals(oneWayBicycle)) {
permissionsFront = permissionsFront.remove(StreetTraversalPermission.BICYCLE);
}
if (OSMWithTags.isFalse(oneWayBicycle) || way.isTagTrue("bicycle:backwards")) {
if (permissions.allows(StreetTraversalPermission.BICYCLE)) {
permissionsFront = permissionsFront.add(StreetTraversalPermission.BICYCLE);
permissionsBack = permissionsBack.add(StreetTraversalPermission.BICYCLE);
}
}
// any cycleway which is opposite* allows contraflow biking
String cycleway = way.getTag("cycleway");
String cyclewayLeft = way.getTag("cycleway:left");
String cyclewayRight = way.getTag("cycleway:right");
if ((cycleway != null && cycleway.startsWith("opposite"))
|| (cyclewayLeft != null && cyclewayLeft.startsWith("opposite"))
|| (cyclewayRight != null && cyclewayRight.startsWith("opposite"))) {
permissionsBack = permissionsBack.add(StreetTraversalPermission.BICYCLE);
}
String access = way.getTag("access");
boolean noThruTraffic = "destination".equals(access) || "private".equals(access)
|| "customers".equals(access) || "delivery".equals(access)
|| "forestry".equals(access) || "agricultural".equals(access);
if (permissionsFront != StreetTraversalPermission.NONE) {
street = getEdgeForStreet(start, end, way, startNode, d, permissionsFront,
geometry, false);
street.setNoThruTraffic(noThruTraffic);
}
if (permissionsBack != StreetTraversalPermission.NONE) {
backStreet = getEdgeForStreet(end, start, way, startNode, d, permissionsBack,
backGeometry, true);
backStreet.setNoThruTraffic(noThruTraffic);
}
/* mark edges that are on roundabouts */
if ("roundabout".equals(tags.get("junction"))) {
if (street != null)
street.setRoundabout(true);
if (backStreet != null)
backStreet.setRoundabout(true);
}
return new P2<PlainStreetEdge>(street, backStreet);
}
private PlainStreetEdge getEdgeForStreet(IntersectionVertex start, IntersectionVertex end,
OSMWithTags way, long startNode, double length,
StreetTraversalPermission permissions, LineString geometry, boolean back) {
String id = "way " + way.getId() + " from " + startNode;
id = unique(id);
String name = way.getAssumedName();
if (customNamer != null) {
name = customNamer.name(way, name);
}
if (name == null) {
name = id;
}
boolean steps = "steps".equals(way.getTag("highway"));
if (steps) {
// consider the elevation gain of stairs, roughly
length *= 2;
}
PlainStreetEdge street = new PlainStreetEdge(start, end, geometry, name, length,
permissions, back);
street.setId(id);
if (!way.hasTag("name")) {
street.setBogusName(true);
}
street.setStairs(steps);
/* TODO: This should probably generalized somehow? */
if (way.isTagFalse("wheelchair") || (steps && !way.isTagTrue("wheelchair"))) {
street.setWheelchairAccessible(false);
}
street.setSlopeOverride(wayPropertySet.getSlopeOverride(way));
if (customNamer != null) {
customNamer.nameWithEdge(way, street);
}
return street;
}
private StreetTraversalPermission getPermissionsForEntity(OSMWithTags entity,
StreetTraversalPermission def) {
Map<String, String> tags = entity.getTags();
StreetTraversalPermission permission = null;
String highway = tags.get("highway");
String cycleway = tags.get("cycleway");
String access = tags.get("access");
String motorcar = tags.get("motorcar");
String bicycle = tags.get("bicycle");
String foot = tags.get("foot");
/*
* Only a few tags are examined here, because we only care about modes supported by OTP
* (wheelchairs are not of concern here)
*
* Only a few values are checked for, all other values are presumed to be permissive (=>
* This may not be perfect, but is closer to reality, since most people don't follow the
* rules perfectly ;-)
*/
if (access != null) {
if ("no".equals(access) || "license".equals(access)) {
// this can actually be overridden
permission = StreetTraversalPermission.NONE;
if (entity.doesTagAllowAccess("motorcar")) {
permission = permission.add(StreetTraversalPermission.CAR);
}
if (entity.doesTagAllowAccess("bicycle")) {
permission = permission.add(StreetTraversalPermission.BICYCLE);
}
if (entity.doesTagAllowAccess("foot")) {
permission = permission.add(StreetTraversalPermission.PEDESTRIAN);
}
} else {
permission = def;
}
} else if (motorcar != null || bicycle != null || foot != null) {
permission = def;
}
if (motorcar != null) {
if ("no".equals(motorcar) || "license".equals(motorcar)) {
permission = permission.remove(StreetTraversalPermission.CAR);
} else {
permission = permission.add(StreetTraversalPermission.CAR);
}
}
if (bicycle != null) {
if ("no".equals(bicycle) || "license".equals(bicycle)) {
permission = permission.remove(StreetTraversalPermission.BICYCLE);
} else {
permission = permission.add(StreetTraversalPermission.BICYCLE);
}
}
if (foot != null) {
if ("no".equals(foot) || "license".equals(foot)) {
permission = permission.remove(StreetTraversalPermission.PEDESTRIAN);
} else {
permission = permission.add(StreetTraversalPermission.PEDESTRIAN);
}
}
if (highway != null) {
if ("construction".equals(highway)) {
permission = StreetTraversalPermission.NONE;
}
} else {
if ("construction".equals(cycleway)) {
permission = StreetTraversalPermission.NONE;
}
}
if (permission == null)
return def;
return permission;
}
/**
* Is this a multi-level node that should be decomposed to multiple coincident nodes?
* Currently returns true only for elevators.
*
* @param node
* @return whether the node is multi-level
* @author mattwigway
*/
private boolean isMultiLevelNode(OSMNode node) {
return node.hasTag("highway") && "elevator".equals(node.getTag("highway"));
}
/**
* Record the level of the way for this node, e.g. if the way is at level 5, mark that this
* node is active at level 5.
*
* @param the way that has the level
* @param the node to record for
* @author mattwigway
*/
private IntersectionVertex recordLevel(OSMNode node, OSMWithTags way) {
OSMLevel level = wayLevels.get(way);
HashMap<OSMLevel, IntersectionVertex> vertices;
long nodeId = node.getId();
if (multiLevelNodes.containsKey(nodeId)) {
vertices = multiLevelNodes.get(nodeId);
} else {
vertices = new HashMap<OSMLevel, IntersectionVertex>();
multiLevelNodes.put(nodeId, vertices);
}
if (!vertices.containsKey(level)) {
Coordinate coordinate = getCoordinate(node);
String label = "osm node " + nodeId + " at level " + level.shortName;
IntersectionVertex vertex = new IntersectionVertex(graph, label, coordinate.x,
coordinate.y, label);
vertices.put(level, vertex);
// multilevel nodes should also undergo turn-conversion
endpoints.add(vertex);
return vertex;
}
return vertices.get(level);
}
/**
* Make or get a shared vertex for flat intersections, or one vertex per level for
* multilevel nodes like elevators. When there is an elevator or other Z-dimension
* discontinuity, a single node can appear in several ways at different levels.
*
* @param node The node to fetch a label for.
* @param way The way it is connected to (for fetching level information).
* @return vertex The graph vertex.
*/
private IntersectionVertex getVertexForOsmNode(OSMNode node, OSMWithTags way) {
// If the node should be decomposed to multiple levels,
// use the numeric level because it is unique, the human level may not be (although
// it will likely lead to some head-scratching if it is not).
IntersectionVertex iv = null;
if (isMultiLevelNode(node)) {
// make a separate node for every level
return recordLevel(node, way);
}
// single-level case
long nid = node.getId();
iv = intersectionNodes.get(nid);
if (iv == null) {
Coordinate coordinate = getCoordinate(node);
String label = "osm node " + nid;
iv = new IntersectionVertex(graph, label, coordinate.x, coordinate.y, label);
intersectionNodes.put(nid, iv);
endpoints.add(iv);
}
return iv;
}
}
public CustomNamer getCustomNamer() {
return customNamer;
}
public void setCustomNamer(CustomNamer customNamer) {
this.customNamer = customNamer;
}
}
| true | true | public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
this.graph = graph;
// handle turn restrictions, road names, and level maps in relations
processRelations();
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
initIntersectionNodes();
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
for (OSMWay way : _ways.values()) {
if (wayIndex % 10000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
if (!way.hasTag("name")) {
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
}
Set<Alert> note = wayPropertySet.getNoteForWay(way);
Set<Alert> wheelchairNote = getWheelchairNotes(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way,
wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
IntersectionVertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
getLevelsForWay(way);
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry and
* ele tags. For nodes which are shared, create endpoints and StreetVertex
* instances.
*/
Long startNode = null;
//where the current edge should start
OSMNode osmStartNode = null;
List<ElevationPoint> elevationPoints = new ArrayList<ElevationPoint>();
double distance = 0;
for (int i = 0; i < nodes.size() - 1; i++) {
OSMNode segmentStartOSMNode = _nodes.get(nodes.get(i));
if (segmentStartOSMNode == null) {
continue;
}
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = segmentStartOSMNode;
elevationPoints.clear();
}
//where the current edge might end
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
String ele = segmentStartOSMNode.getTag("ele");
if (ele != null) {
elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele)));
}
distance += DistanceLibrary.distance(segmentStartOSMNode.getLat(), segmentStartOSMNode.getLon(),
osmEndNode.getLat(), osmEndNode.getLon());
if (intersectionNodes.containsKey(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
ele = osmEndNode.getTag("ele");
if (ele != null) {
elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele)));
}
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) { // first iteration on this way
// make or get a shared vertex for flat intersections,
// one vertex per level for multilevel nodes like elevators
startEndpoint = getVertexForOsmNode(osmStartNode, way);
} else { // subsequent iterations
startEndpoint = endEndpoint;
}
endEndpoint = getVertexForOsmNode(osmEndNode, way);
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety);
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
if (note != null) {
street.setNote(note);
}
if (wheelchairNote != null) {
street.setWheelchairNote(wheelchairNote);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
double safety = wayData.getSafetyFeatures().getSecond();
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety);
if (note != null) {
backStreet.setNote(note);
}
if (wheelchairNote != null) {
backStreet.setWheelchairNote(wheelchairNote);
}
}
storeExtraElevationData(elevationPoints, street, backStreet, distance);
applyEdgesToTurnRestrictions(way, startNode, endNode, street, backStreet);
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
} // END loop over OSM ways
buildElevatorEdges(graph);
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
if (customNamer != null) {
customNamer.postprocess(graph);
}
//generate elevation profiles
Map<EdgeWithElevation, List<ElevationPoint>> data = extraElevationData.data;
for (Map.Entry<EdgeWithElevation, List<ElevationPoint>> entry : data.entrySet()) {
EdgeWithElevation edge = entry.getKey();
List<ElevationPoint> points = entry.getValue();
Collections.sort(points);
if (points.size() == 1) {
ElevationPoint firstPoint = points.get(0);
ElevationPoint endPoint = new ElevationPoint(edge.getDistance(), firstPoint.ele);
points.add(endPoint);
}
Coordinate[] coords = new Coordinate[points.size()];
int i = 0;
for (ElevationPoint p : points) {
double d = p.distanceAlongShape;
if (i == 0) {
d = 0;
} else if (i == points.size() - 1) {
d = edge.getDistance();
}
coords[i++] = new Coordinate(d, p.ele);
}
edge.setElevationProfile(new PackedCoordinateSequence.Double(coords), true);
}
applyBikeSafetyFactor(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
} // END buildGraph()
| public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
this.graph = graph;
// handle turn restrictions, road names, and level maps in relations
processRelations();
// Remove all simple islands
_nodes.keySet().retainAll(_nodesWithNeighbors);
long wayIndex = 0;
// figure out which nodes that are actually intersections
initIntersectionNodes();
GeometryFactory geometryFactory = new GeometryFactory();
/* build an ordinary graph, which we will convert to an edge-based graph */
for (OSMWay way : _ways.values()) {
if (wayIndex % 10000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
WayProperties wayData = wayPropertySet.getDataForWay(way);
if (!way.hasTag("name")) {
String creativeName = wayPropertySet.getCreativeNameForWay(way);
if (creativeName != null) {
way.addTag("otp:gen_name", creativeName);
}
}
Set<Alert> note = wayPropertySet.getNoteForWay(way);
Set<Alert> wheelchairNote = getWheelchairNotes(way);
StreetTraversalPermission permissions = getPermissionsForEntity(way,
wayData.getPermission());
if (permissions == StreetTraversalPermission.NONE)
continue;
List<Long> nodes = way.getNodeRefs();
IntersectionVertex startEndpoint = null, endEndpoint = null;
ArrayList<Coordinate> segmentCoordinates = new ArrayList<Coordinate>();
getLevelsForWay(way);
/*
* Traverse through all the nodes of this edge. For nodes which are not shared with
* any other edge, do not create endpoints -- just accumulate them for geometry and
* ele tags. For nodes which are shared, create endpoints and StreetVertex
* instances.
*/
Long startNode = null;
//where the current edge should start
OSMNode osmStartNode = null;
List<ElevationPoint> elevationPoints = new ArrayList<ElevationPoint>();
double distance = 0;
for (int i = 0; i < nodes.size() - 1; i++) {
OSMNode segmentStartOSMNode = _nodes.get(nodes.get(i));
if (segmentStartOSMNode == null) {
continue;
}
Long endNode = nodes.get(i + 1);
if (osmStartNode == null) {
startNode = nodes.get(i);
osmStartNode = segmentStartOSMNode;
elevationPoints.clear();
}
//where the current edge might end
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
LineString geometry;
/*
* skip vertices that are not intersections, except that we use them for
* geometry
*/
if (segmentCoordinates.size() == 0) {
segmentCoordinates.add(getCoordinate(osmStartNode));
}
String ele = segmentStartOSMNode.getTag("ele");
if (ele != null) {
ele = ele.toLowerCase();
double unit = 1;
if (ele.endsWith("m")) {
ele = ele.replaceFirst("\\s*m", "");
} else if (ele.endsWith("ft")) {
ele = ele.replaceFirst("\\s*ft", "");
unit = 0.3048;
}
elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele) * unit));
}
distance += DistanceLibrary.distance(segmentStartOSMNode.getLat(), segmentStartOSMNode.getLon(),
osmEndNode.getLat(), osmEndNode.getLon());
if (intersectionNodes.containsKey(endNode) || i == nodes.size() - 2) {
segmentCoordinates.add(getCoordinate(osmEndNode));
ele = osmEndNode.getTag("ele");
if (ele != null) {
elevationPoints.add(new ElevationPoint(distance, Double.parseDouble(ele)));
}
geometry = geometryFactory.createLineString(segmentCoordinates
.toArray(new Coordinate[0]));
segmentCoordinates.clear();
} else {
segmentCoordinates.add(getCoordinate(osmEndNode));
continue;
}
/* generate endpoints */
if (startEndpoint == null) { // first iteration on this way
// make or get a shared vertex for flat intersections,
// one vertex per level for multilevel nodes like elevators
startEndpoint = getVertexForOsmNode(osmStartNode, way);
} else { // subsequent iterations
startEndpoint = endEndpoint;
}
endEndpoint = getVertexForOsmNode(osmEndNode, way);
P2<PlainStreetEdge> streets = getEdgesForStreet(startEndpoint, endEndpoint,
way, i, permissions, geometry);
PlainStreetEdge street = streets.getFirst();
if (street != null) {
double safety = wayData.getSafetyFeatures().getFirst();
street.setBicycleSafetyEffectiveLength(street.getLength() * safety);
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
if (note != null) {
street.setNote(note);
}
if (wheelchairNote != null) {
street.setWheelchairNote(wheelchairNote);
}
}
PlainStreetEdge backStreet = streets.getSecond();
if (backStreet != null) {
double safety = wayData.getSafetyFeatures().getSecond();
if (safety < bestBikeSafety) {
bestBikeSafety = safety;
}
backStreet.setBicycleSafetyEffectiveLength(backStreet.getLength() * safety);
if (note != null) {
backStreet.setNote(note);
}
if (wheelchairNote != null) {
backStreet.setWheelchairNote(wheelchairNote);
}
}
storeExtraElevationData(elevationPoints, street, backStreet, distance);
applyEdgesToTurnRestrictions(way, startNode, endNode, street, backStreet);
startNode = endNode;
osmStartNode = _nodes.get(startNode);
}
} // END loop over OSM ways
buildElevatorEdges(graph);
/* unify turn restrictions */
Map<Edge, TurnRestriction> turnRestrictions = new HashMap<Edge, TurnRestriction>();
for (TurnRestriction restriction : turnRestrictionsByTag.values()) {
turnRestrictions.put(restriction.from, restriction);
}
if (customNamer != null) {
customNamer.postprocess(graph);
}
//generate elevation profiles
Map<EdgeWithElevation, List<ElevationPoint>> data = extraElevationData.data;
for (Map.Entry<EdgeWithElevation, List<ElevationPoint>> entry : data.entrySet()) {
EdgeWithElevation edge = entry.getKey();
List<ElevationPoint> points = entry.getValue();
Collections.sort(points);
if (points.size() == 1) {
ElevationPoint firstPoint = points.get(0);
ElevationPoint endPoint = new ElevationPoint(edge.getDistance(), firstPoint.ele);
points.add(endPoint);
}
Coordinate[] coords = new Coordinate[points.size()];
int i = 0;
for (ElevationPoint p : points) {
double d = p.distanceAlongShape;
if (i == 0) {
d = 0;
} else if (i == points.size() - 1) {
d = edge.getDistance();
}
coords[i++] = new Coordinate(d, p.ele);
}
edge.setElevationProfile(new PackedCoordinateSequence.Double(coords), true);
}
applyBikeSafetyFactor(graph);
StreetUtils.makeEdgeBased(graph, endpoints, turnRestrictions);
} // END buildGraph()
|
diff --git a/src/com/herocraftonline/dev/heroes/command/commands/SelectSpecialtyCommand.java b/src/com/herocraftonline/dev/heroes/command/commands/SelectSpecialtyCommand.java
index c3805bf..af48e13 100644
--- a/src/com/herocraftonline/dev/heroes/command/commands/SelectSpecialtyCommand.java
+++ b/src/com/herocraftonline/dev/heroes/command/commands/SelectSpecialtyCommand.java
@@ -1,52 +1,56 @@
package com.herocraftonline.dev.heroes.command.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.classes.ClassManager;
import com.herocraftonline.dev.heroes.classes.HeroClass;
import com.herocraftonline.dev.heroes.command.BaseCommand;
import com.herocraftonline.dev.heroes.persistence.Hero;
import com.herocraftonline.dev.heroes.persistence.HeroManager;
import com.herocraftonline.dev.heroes.util.Properties;
public class SelectSpecialtyCommand extends BaseCommand {
Properties prop = plugin.getConfigManager().getProperties();
public SelectSpecialtyCommand(Heroes plugin) {
super(plugin);
name = "Select Specialty";
description = "Allows you to advance from a primary class to it's specialty";
usage = "/hero specialty §9<type>";
minArgs = 1;
maxArgs = 1;
identifiers.add("hero specialty");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
HeroManager heroManager = plugin.getHeroManager();
ClassManager classManager = plugin.getClassManager();
Hero hero = heroManager.getHero(player);
HeroClass playerClass = hero.getPlayerClass();
- if (playerClass.isPrimary() && prop.getLevel(hero.getExperience()) > prop.classSwitchLevel) {
- HeroClass subClass = classManager.getClass(args[0]);
- if (subClass != null) {
- if (subClass.getParent() == playerClass) {
- hero.setPlayerClass(subClass);
- plugin.getMessager().send(player, "Well done $1!", subClass.getName());
+ if (playerClass.isPrimary()) {
+ if (prop.getLevel(hero.getExperience()) >= prop.classSwitchLevel) {
+ HeroClass subClass = classManager.getClass(args[0]);
+ if (subClass != null) {
+ if (subClass.getParent() == playerClass) {
+ hero.setPlayerClass(subClass);
+ plugin.getMessager().send(player, "Well done $1!", subClass.getName());
+ } else {
+ plugin.getMessager().send(player, "Sorry, that specialty doesn't belong to $1.", playerClass.getName());
+ }
} else {
- plugin.getMessager().send(player, "Sorry, that specialty doesn't belong to $1.", playerClass.getName());
+ plugin.getMessager().send(player, "Sorry, that isn't a specialty!");
}
} else {
- plugin.getMessager().send(player, "Sorry, that isn't a specialty!");
+ plugin.getMessager().send(player, "You must master your profession before choosing a specialty.");
}
} else {
plugin.getMessager().send(player, "You have already selected a specialty!");
}
}
}
}
| false | true | public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
HeroManager heroManager = plugin.getHeroManager();
ClassManager classManager = plugin.getClassManager();
Hero hero = heroManager.getHero(player);
HeroClass playerClass = hero.getPlayerClass();
if (playerClass.isPrimary() && prop.getLevel(hero.getExperience()) > prop.classSwitchLevel) {
HeroClass subClass = classManager.getClass(args[0]);
if (subClass != null) {
if (subClass.getParent() == playerClass) {
hero.setPlayerClass(subClass);
plugin.getMessager().send(player, "Well done $1!", subClass.getName());
} else {
plugin.getMessager().send(player, "Sorry, that specialty doesn't belong to $1.", playerClass.getName());
}
} else {
plugin.getMessager().send(player, "Sorry, that isn't a specialty!");
}
} else {
plugin.getMessager().send(player, "You have already selected a specialty!");
}
}
}
| public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
HeroManager heroManager = plugin.getHeroManager();
ClassManager classManager = plugin.getClassManager();
Hero hero = heroManager.getHero(player);
HeroClass playerClass = hero.getPlayerClass();
if (playerClass.isPrimary()) {
if (prop.getLevel(hero.getExperience()) >= prop.classSwitchLevel) {
HeroClass subClass = classManager.getClass(args[0]);
if (subClass != null) {
if (subClass.getParent() == playerClass) {
hero.setPlayerClass(subClass);
plugin.getMessager().send(player, "Well done $1!", subClass.getName());
} else {
plugin.getMessager().send(player, "Sorry, that specialty doesn't belong to $1.", playerClass.getName());
}
} else {
plugin.getMessager().send(player, "Sorry, that isn't a specialty!");
}
} else {
plugin.getMessager().send(player, "You must master your profession before choosing a specialty.");
}
} else {
plugin.getMessager().send(player, "You have already selected a specialty!");
}
}
}
|
diff --git a/src/com/vividsolutions/jump/workbench/imagery/ecw/ECWImageFactory.java b/src/com/vividsolutions/jump/workbench/imagery/ecw/ECWImageFactory.java
index c54312b7..3fb7df4f 100644
--- a/src/com/vividsolutions/jump/workbench/imagery/ecw/ECWImageFactory.java
+++ b/src/com/vividsolutions/jump/workbench/imagery/ecw/ECWImageFactory.java
@@ -1,85 +1,85 @@
package com.vividsolutions.jump.workbench.imagery.ecw;
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* Copyright (C) 2003 Vivid Solutions
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.JUMPException;
import com.vividsolutions.jump.workbench.WorkbenchContext;
import com.vividsolutions.jump.workbench.imagery.ReferencedImage;
import com.vividsolutions.jump.workbench.imagery.ReferencedImageFactory;
/**
*/
public class ECWImageFactory implements ReferencedImageFactory {
public static final String TYPE_NAME = "ECW";
final static String sNotInstalled=I18N.get("org.openjump.core.ui.plugin.layer.AddSIDLayerPlugIn.not-installed");
public ECWImageFactory() {
}
public String getTypeName() {
return TYPE_NAME;
}
public ReferencedImage createImage(String location) throws JUMPException {
return new ECWImage(location);
}
public String getDescription() {
return "Enhanced Compressed Wavelet";
}
public String[] getExtensions() {
return new String[] { "ecw" };
}
public boolean isEditableImage(String location) {
return false;
}
public boolean isAvailable(WorkbenchContext context) {
Class c = null;
try{
c = this.getClass().getClassLoader().loadClass(
JNCSRendererProxy.RENDERER_CLASS);
}catch(ClassNotFoundException e){
// eat it
- System.out.println("ECW loader class " + c.toString() + " " + sNotInstalled);
+ System.out.println("ECW loader class " + JNCSRendererProxy.RENDERER_CLASS + " " + sNotInstalled);
return false;
}
System.out.println("found ECW loader class");
return c != null;
}
}
| true | true | public boolean isAvailable(WorkbenchContext context) {
Class c = null;
try{
c = this.getClass().getClassLoader().loadClass(
JNCSRendererProxy.RENDERER_CLASS);
}catch(ClassNotFoundException e){
// eat it
System.out.println("ECW loader class " + c.toString() + " " + sNotInstalled);
return false;
}
System.out.println("found ECW loader class");
return c != null;
}
| public boolean isAvailable(WorkbenchContext context) {
Class c = null;
try{
c = this.getClass().getClassLoader().loadClass(
JNCSRendererProxy.RENDERER_CLASS);
}catch(ClassNotFoundException e){
// eat it
System.out.println("ECW loader class " + JNCSRendererProxy.RENDERER_CLASS + " " + sNotInstalled);
return false;
}
System.out.println("found ECW loader class");
return c != null;
}
|
diff --git a/jython/src/org/python/core/PyGetSetDescr.java b/jython/src/org/python/core/PyGetSetDescr.java
index d1f7118d..f47b8d99 100644
--- a/jython/src/org/python/core/PyGetSetDescr.java
+++ b/jython/src/org/python/core/PyGetSetDescr.java
@@ -1,158 +1,158 @@
package org.python.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class PyGetSetDescr extends PyDescriptor {
private Method get_meth;
private Method set_meth;
private Method del_meth;
private Class getset_type;
public PyGetSetDescr(PyType dtype,
String name,
Class c,
String get,
String set) {
this(dtype, name, c, get, set, null);
}
public PyGetSetDescr(String name, Class c, String get, String set) {
this(PyType.fromClass(c), name, c, get, set, null);
}
public PyGetSetDescr(PyType dtype,
String name,
Class c,
String get,
String set,
String del) {
this.name = name;
this.dtype = dtype;
try {
get_meth = c.getMethod(get, new Class[] {});
} catch(NoSuchMethodException e) {
- throw Py.SystemError("bogus getset spec");
+ throw Py.SystemError("method "+get+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(get_meth.getModifiers()))
- throw Py.SystemError("static getset not supported");
+ throw Py.SystemError("static "+get+" not supported: "+c.getName());
getset_type = get_meth.getReturnType();
if(set != null) {
try {
set_meth = c.getMethod(set, new Class[] {getset_type});
} catch(NoSuchMethodException e) {
- throw Py.SystemError("bogus getset spec");
+ throw Py.SystemError("method "+set+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(set_meth.getModifiers()))
- throw Py.SystemError("static getset not supported");
+ throw Py.SystemError("static "+set+" not supported: "+c.getName());
}
if(del != null) {
try {
del_meth = c.getMethod(del, new Class[] {});
} catch(NoSuchMethodException e) {
- throw Py.SystemError("bogus getset spec");
+ throw Py.SystemError("method "+set+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(del_meth.getModifiers()))
- throw Py.SystemError("static getset not supported");
+ throw Py.SystemError("static "+del+" not supported: "+c.getName());
}
}
public PyGetSetDescr(String name, Class c, String get, String set, String del) {
this(PyType.fromClass(c), name, c, get, set, del);
}
public String toString() {
return "<attribute '" + name + "' of '" + dtype.fastGetName()
+ "' objects>";
}
/**
* @see org.python.core.PyObject#__get__(org.python.core.PyObject,
* org.python.core.PyObject)
*/
public PyObject __get__(PyObject obj, PyObject type) {
try {
if(obj != null) {
PyType objtype = obj.getType();
if(objtype != dtype && !objtype.isSubType(dtype))
throw get_wrongtype(objtype);
Object v = get_meth.invoke(obj, new Object[0]);
if(v == null) {
obj.noAttributeError(name);
}
return Py.java2py(v);
}
return this;
} catch(IllegalArgumentException e) {
throw Py.JavaError(e);
} catch(IllegalAccessException e) {
throw Py.JavaError(e); // unexpected
} catch(InvocationTargetException e) {
throw Py.JavaError(e);
}
}
/**
* @see org.python.core.PyObject#__set__(org.python.core.PyObject,
* org.python.core.PyObject)
*/
public void __set__(PyObject obj, PyObject value) {
try {
// obj != null
PyType objtype = obj.getType();
if(objtype != dtype && !objtype.isSubType(dtype))
throw get_wrongtype(objtype);
Object converted = value.__tojava__(getset_type);
if(converted == Py.NoConversion) {
throw Py.TypeError(""); // xxx
}
set_meth.invoke(obj, new Object[] {converted});
} catch(IllegalArgumentException e) {
throw Py.JavaError(e);
} catch(IllegalAccessException e) {
throw Py.JavaError(e); // unexpected
} catch(InvocationTargetException e) {
throw Py.JavaError(e);
}
}
public void __delete__(PyObject obj) {
try {
if(obj != null) {
PyType objtype = obj.getType();
if(objtype != dtype && !objtype.isSubType(dtype))
throw get_wrongtype(objtype);
del_meth.invoke(obj, new Object[0]);
}
} catch(IllegalArgumentException e) {
throw Py.JavaError(e);
} catch(IllegalAccessException e) {
throw Py.JavaError(e); // unexpected
} catch(InvocationTargetException e) {
throw Py.JavaError(e);
}
}
/**
* @see org.python.core.PyObject#implementsDescrSet()
*/
public boolean implementsDescrSet() {
return set_meth != null;
}
public boolean implementsDescrDelete() {
return del_meth != null;
}
/**
* @see org.python.core.PyObject#isDataDescr()
*/
public boolean isDataDescr() {
return true;
}
}
| false | true | public PyGetSetDescr(PyType dtype,
String name,
Class c,
String get,
String set,
String del) {
this.name = name;
this.dtype = dtype;
try {
get_meth = c.getMethod(get, new Class[] {});
} catch(NoSuchMethodException e) {
throw Py.SystemError("bogus getset spec");
}
if(Modifier.isStatic(get_meth.getModifiers()))
throw Py.SystemError("static getset not supported");
getset_type = get_meth.getReturnType();
if(set != null) {
try {
set_meth = c.getMethod(set, new Class[] {getset_type});
} catch(NoSuchMethodException e) {
throw Py.SystemError("bogus getset spec");
}
if(Modifier.isStatic(set_meth.getModifiers()))
throw Py.SystemError("static getset not supported");
}
if(del != null) {
try {
del_meth = c.getMethod(del, new Class[] {});
} catch(NoSuchMethodException e) {
throw Py.SystemError("bogus getset spec");
}
if(Modifier.isStatic(del_meth.getModifiers()))
throw Py.SystemError("static getset not supported");
}
}
| public PyGetSetDescr(PyType dtype,
String name,
Class c,
String get,
String set,
String del) {
this.name = name;
this.dtype = dtype;
try {
get_meth = c.getMethod(get, new Class[] {});
} catch(NoSuchMethodException e) {
throw Py.SystemError("method "+get+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(get_meth.getModifiers()))
throw Py.SystemError("static "+get+" not supported: "+c.getName());
getset_type = get_meth.getReturnType();
if(set != null) {
try {
set_meth = c.getMethod(set, new Class[] {getset_type});
} catch(NoSuchMethodException e) {
throw Py.SystemError("method "+set+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(set_meth.getModifiers()))
throw Py.SystemError("static "+set+" not supported: "+c.getName());
}
if(del != null) {
try {
del_meth = c.getMethod(del, new Class[] {});
} catch(NoSuchMethodException e) {
throw Py.SystemError("method "+set+" doesn't exist: "+c.getName());
}
if(Modifier.isStatic(del_meth.getModifiers()))
throw Py.SystemError("static "+del+" not supported: "+c.getName());
}
}
|
diff --git a/Project3/src/Driver.java b/Project3/src/Driver.java
index 2eb0a7b..3a08a93 100644
--- a/Project3/src/Driver.java
+++ b/Project3/src/Driver.java
@@ -1,246 +1,246 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
* Project #3
* CS 2334, Section 010
* Oct 1, 2013
* <P>
* This class will allow you to read a file of publication information, search through the data,
* write data onto a file, and display bar graphs of the data.
* </P>
*@version 1.0
*/
public class Driver implements Serializable {
/**
* serial ID
*/
private static final long serialVersionUID = 5481149857232568707L;
/**
* list of publishers
*/
static HashMap<String, Publication> pubList;
/**
* list of authors
*/
static HashMap<String, Author> authorList;
public static void main (String[] args) throws IOException{
//Scanner for user input data
Scanner in = new Scanner(System.in);
//For loop for repeating search
for(int i=0; i==0;){
//Ask for and read in the file
String filename = JOptionPane.showInputDialog ( "Please enter the name of the file" );
if(filename == null)
System.exit(-1);
Parser p = new Parser(filename);
//Save input as the choice
String choice = JOptionPane.showInputDialog ( "Choose a criteria to search by entering the coressponding digit: \n\n1. Name of Author \n2. Name of Paper/Article \n3. Exit the Program" );
if(choice == null)
System.exit(-1);
int num = Integer.valueOf(choice);
//Manages choice using if statements
String search = "";
int testIfAuthor = 0; //Tests to make sure search string is an author name, for use later when creating graph
if(num==1){ testIfAuthor = 1; search = JOptionPane.showInputDialog ( "You are searching by Name of Author. Please enter a name to search for" );}
else if(num==2){testIfAuthor = 0;search = JOptionPane.showInputDialog ( "You are searching by Name of Article/Paper. Please enter a name to search for");}
else if(num==3){i=1; System.exit(-1);}
else JOptionPane.showMessageDialog(null, "Please enter a valid option number.");
//Search for data here using specified criteria type
ArrayList<Publication> results = new ArrayList<Publication>();
//the results of the search
Boolean resultsBool = false;
//ArrayList of Publications made from Parser
pubList = new HashMap<String, Publication>();
pubList = p.getPublications();
authorList = new HashMap<String, Author>();
authorList = p.getAuthors();
//Search through publications
if(num==1)
{
Author foundAuthor = authorList.get(search);
if(foundAuthor != null)
{
ArrayList<Publication> foundAuthorPapers = foundAuthor.getPublishedPapers();
for(Publication paper : foundAuthorPapers)
{
results.add(pubList.get(paper.getTitlePaper()));
}
resultsBool = true;
}
}
else if(num==2)
{
Publication foundPub = pubList.get(search);
if(foundPub != null)
{
- results.add(pubList.get(foundPub));
+ results.add(pubList.get(search));
resultsBool = true;
}
}
//JOptionPane that displays search results
if(resultsBool==true){
Object[] options = {"Author",
"Paper Title",
"Date"};
int sortingMethod = JOptionPane.showOptionDialog(null,
"Sort by Author or Paper Title?",
"What Sorting Method to Use?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
results.get(0);
Publication.compareMethod = sortingMethod;
Collections.sort(results);
String out="";
for(Publication Pub : results)
{
out+=Pub.toString() + "\n";
}
JOptionPane.showMessageDialog(null, out);
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Would you like to save the results?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
//Write to file
writePublications("Results.txt", out);
JOptionPane.showMessageDialog(null, "The results were written to the file Results.txt");
} else
{
//No option
JOptionPane.showMessageDialog(null, "The results were not saved.");
}
//test to see if user searched for author, if not ask for author to use in graphs
if(testIfAuthor == 0){
search = JOptionPane.showInputDialog ( "Please enter an Author name to use in the graphs" );
}
//graphing
for(int l=0;l==0;){
//Yes and No JOptionPane used to show a graph
Object[] graphOptions = {"TP",
"PY",
"CPY",
"JAY",
"NC",
"None"};
int graphChoice = JOptionPane.showOptionDialog(null,
"Would you like to graph information for this author? \nIf yes, please choose one of the following types of graph: \n\nTP: Type of Publication \nPY: Publications per Year \nCPY: Conference Papers per Year \nJAY: Journal Articles per Year \nNC: Number of co-authors per publication",
"Would you like to create a graph using this information?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
graphOptions,
graphOptions[5]);
if(graphChoice<5){
Graph newGraph = new Graph((String) graphOptions[graphChoice],search, authorList);
newGraph.displayGraph();
if (JOptionPane.showConfirmDialog(null, "Would you like to see another graph?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
l=0;
}
else {
l=1;
}
}
else if(graphChoice==5){
l=1;
}
}
}
else if(resultsBool==false) JOptionPane.showMessageDialog(null, "There were no publications with that matched your search.");
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search again?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
//Yes and No JOptionPane used to search using a different file or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search a different file?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
/**
* writes resultant database to disk
*
* @throws IOException
*/
public static void writePublications(String filename, String results) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(filename);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(results);
objectOutputStream.close();
}
/**
* Writes text file to disk
*/
public static void writeFileString(){
}
/**
* Writes binary file to disk
*/
public static void writeFileBin(){
}
}
| true | true | public static void main (String[] args) throws IOException{
//Scanner for user input data
Scanner in = new Scanner(System.in);
//For loop for repeating search
for(int i=0; i==0;){
//Ask for and read in the file
String filename = JOptionPane.showInputDialog ( "Please enter the name of the file" );
if(filename == null)
System.exit(-1);
Parser p = new Parser(filename);
//Save input as the choice
String choice = JOptionPane.showInputDialog ( "Choose a criteria to search by entering the coressponding digit: \n\n1. Name of Author \n2. Name of Paper/Article \n3. Exit the Program" );
if(choice == null)
System.exit(-1);
int num = Integer.valueOf(choice);
//Manages choice using if statements
String search = "";
int testIfAuthor = 0; //Tests to make sure search string is an author name, for use later when creating graph
if(num==1){ testIfAuthor = 1; search = JOptionPane.showInputDialog ( "You are searching by Name of Author. Please enter a name to search for" );}
else if(num==2){testIfAuthor = 0;search = JOptionPane.showInputDialog ( "You are searching by Name of Article/Paper. Please enter a name to search for");}
else if(num==3){i=1; System.exit(-1);}
else JOptionPane.showMessageDialog(null, "Please enter a valid option number.");
//Search for data here using specified criteria type
ArrayList<Publication> results = new ArrayList<Publication>();
//the results of the search
Boolean resultsBool = false;
//ArrayList of Publications made from Parser
pubList = new HashMap<String, Publication>();
pubList = p.getPublications();
authorList = new HashMap<String, Author>();
authorList = p.getAuthors();
//Search through publications
if(num==1)
{
Author foundAuthor = authorList.get(search);
if(foundAuthor != null)
{
ArrayList<Publication> foundAuthorPapers = foundAuthor.getPublishedPapers();
for(Publication paper : foundAuthorPapers)
{
results.add(pubList.get(paper.getTitlePaper()));
}
resultsBool = true;
}
}
else if(num==2)
{
Publication foundPub = pubList.get(search);
if(foundPub != null)
{
results.add(pubList.get(foundPub));
resultsBool = true;
}
}
//JOptionPane that displays search results
if(resultsBool==true){
Object[] options = {"Author",
"Paper Title",
"Date"};
int sortingMethod = JOptionPane.showOptionDialog(null,
"Sort by Author or Paper Title?",
"What Sorting Method to Use?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
results.get(0);
Publication.compareMethod = sortingMethod;
Collections.sort(results);
String out="";
for(Publication Pub : results)
{
out+=Pub.toString() + "\n";
}
JOptionPane.showMessageDialog(null, out);
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Would you like to save the results?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
//Write to file
writePublications("Results.txt", out);
JOptionPane.showMessageDialog(null, "The results were written to the file Results.txt");
} else
{
//No option
JOptionPane.showMessageDialog(null, "The results were not saved.");
}
//test to see if user searched for author, if not ask for author to use in graphs
if(testIfAuthor == 0){
search = JOptionPane.showInputDialog ( "Please enter an Author name to use in the graphs" );
}
//graphing
for(int l=0;l==0;){
//Yes and No JOptionPane used to show a graph
Object[] graphOptions = {"TP",
"PY",
"CPY",
"JAY",
"NC",
"None"};
int graphChoice = JOptionPane.showOptionDialog(null,
"Would you like to graph information for this author? \nIf yes, please choose one of the following types of graph: \n\nTP: Type of Publication \nPY: Publications per Year \nCPY: Conference Papers per Year \nJAY: Journal Articles per Year \nNC: Number of co-authors per publication",
"Would you like to create a graph using this information?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
graphOptions,
graphOptions[5]);
if(graphChoice<5){
Graph newGraph = new Graph((String) graphOptions[graphChoice],search, authorList);
newGraph.displayGraph();
if (JOptionPane.showConfirmDialog(null, "Would you like to see another graph?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
l=0;
}
else {
l=1;
}
}
else if(graphChoice==5){
l=1;
}
}
}
else if(resultsBool==false) JOptionPane.showMessageDialog(null, "There were no publications with that matched your search.");
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search again?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
//Yes and No JOptionPane used to search using a different file or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search a different file?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
| public static void main (String[] args) throws IOException{
//Scanner for user input data
Scanner in = new Scanner(System.in);
//For loop for repeating search
for(int i=0; i==0;){
//Ask for and read in the file
String filename = JOptionPane.showInputDialog ( "Please enter the name of the file" );
if(filename == null)
System.exit(-1);
Parser p = new Parser(filename);
//Save input as the choice
String choice = JOptionPane.showInputDialog ( "Choose a criteria to search by entering the coressponding digit: \n\n1. Name of Author \n2. Name of Paper/Article \n3. Exit the Program" );
if(choice == null)
System.exit(-1);
int num = Integer.valueOf(choice);
//Manages choice using if statements
String search = "";
int testIfAuthor = 0; //Tests to make sure search string is an author name, for use later when creating graph
if(num==1){ testIfAuthor = 1; search = JOptionPane.showInputDialog ( "You are searching by Name of Author. Please enter a name to search for" );}
else if(num==2){testIfAuthor = 0;search = JOptionPane.showInputDialog ( "You are searching by Name of Article/Paper. Please enter a name to search for");}
else if(num==3){i=1; System.exit(-1);}
else JOptionPane.showMessageDialog(null, "Please enter a valid option number.");
//Search for data here using specified criteria type
ArrayList<Publication> results = new ArrayList<Publication>();
//the results of the search
Boolean resultsBool = false;
//ArrayList of Publications made from Parser
pubList = new HashMap<String, Publication>();
pubList = p.getPublications();
authorList = new HashMap<String, Author>();
authorList = p.getAuthors();
//Search through publications
if(num==1)
{
Author foundAuthor = authorList.get(search);
if(foundAuthor != null)
{
ArrayList<Publication> foundAuthorPapers = foundAuthor.getPublishedPapers();
for(Publication paper : foundAuthorPapers)
{
results.add(pubList.get(paper.getTitlePaper()));
}
resultsBool = true;
}
}
else if(num==2)
{
Publication foundPub = pubList.get(search);
if(foundPub != null)
{
results.add(pubList.get(search));
resultsBool = true;
}
}
//JOptionPane that displays search results
if(resultsBool==true){
Object[] options = {"Author",
"Paper Title",
"Date"};
int sortingMethod = JOptionPane.showOptionDialog(null,
"Sort by Author or Paper Title?",
"What Sorting Method to Use?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
results.get(0);
Publication.compareMethod = sortingMethod;
Collections.sort(results);
String out="";
for(Publication Pub : results)
{
out+=Pub.toString() + "\n";
}
JOptionPane.showMessageDialog(null, out);
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Would you like to save the results?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
//Write to file
writePublications("Results.txt", out);
JOptionPane.showMessageDialog(null, "The results were written to the file Results.txt");
} else
{
//No option
JOptionPane.showMessageDialog(null, "The results were not saved.");
}
//test to see if user searched for author, if not ask for author to use in graphs
if(testIfAuthor == 0){
search = JOptionPane.showInputDialog ( "Please enter an Author name to use in the graphs" );
}
//graphing
for(int l=0;l==0;){
//Yes and No JOptionPane used to show a graph
Object[] graphOptions = {"TP",
"PY",
"CPY",
"JAY",
"NC",
"None"};
int graphChoice = JOptionPane.showOptionDialog(null,
"Would you like to graph information for this author? \nIf yes, please choose one of the following types of graph: \n\nTP: Type of Publication \nPY: Publications per Year \nCPY: Conference Papers per Year \nJAY: Journal Articles per Year \nNC: Number of co-authors per publication",
"Would you like to create a graph using this information?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
graphOptions,
graphOptions[5]);
if(graphChoice<5){
Graph newGraph = new Graph((String) graphOptions[graphChoice],search, authorList);
newGraph.displayGraph();
if (JOptionPane.showConfirmDialog(null, "Would you like to see another graph?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
l=0;
}
else {
l=1;
}
}
else if(graphChoice==5){
l=1;
}
}
}
else if(resultsBool==false) JOptionPane.showMessageDialog(null, "There were no publications with that matched your search.");
//Yes and No JOptionPane used to continue searching or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search again?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
//Yes and No JOptionPane used to search using a different file or quit program
if (JOptionPane.showConfirmDialog(null, "Do you wish to search a different file?", "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
//Yes option
} else
{
//No option
in.close();
System.exit(-1);
}
}
|
diff --git a/src/be/ibridge/kettle/job/entry/tableexists/JobEntryTableExists.java b/src/be/ibridge/kettle/job/entry/tableexists/JobEntryTableExists.java
index 265182d8..e8cd5864 100644
--- a/src/be/ibridge/kettle/job/entry/tableexists/JobEntryTableExists.java
+++ b/src/be/ibridge/kettle/job/entry/tableexists/JobEntryTableExists.java
@@ -1,227 +1,227 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.job.entry.tableexists;
import java.util.ArrayList;
import org.eclipse.swt.widgets.Shell;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.job.Job;
import be.ibridge.kettle.job.JobMeta;
import be.ibridge.kettle.job.entry.JobEntryBase;
import be.ibridge.kettle.job.entry.JobEntryDialogInterface;
import be.ibridge.kettle.job.entry.JobEntryInterface;
import be.ibridge.kettle.repository.Repository;
/**
* This defines an SQL job entry.
*
* @author Matt
* @since 05-11-2003
*
*/
public class JobEntryTableExists extends JobEntryBase implements Cloneable, JobEntryInterface
{
private String tablename;
private DatabaseMeta connection;
public JobEntryTableExists(String n)
{
super(n, "");
tablename=null;
connection=null;
setID(-1L);
setType(JobEntryInterface.TYPE_JOBENTRY_TABLE_EXISTS);
}
public JobEntryTableExists()
{
this("");
}
public JobEntryTableExists(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntryTableExists je = (JobEntryTableExists) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer();
retval.append(super.getXML());
retval.append(" "+XMLHandler.addTagValue("tablename", tablename));
retval.append(" "+XMLHandler.addTagValue("connection", connection==null?null:connection.getName()));
return retval.toString();
}
public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
tablename = XMLHandler.getTagValue(entrynode, "tablename");
String dbname = XMLHandler.getTagValue(entrynode, "connection");
connection = Const.findDatabase(databases, dbname);
}
catch(KettleException e)
{
throw new KettleXMLException("Unable to load table exists job entry from XML node", e);
}
}
public void loadRep(Repository rep, long id_jobentry, ArrayList databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
tablename = rep.getJobEntryAttributeString(id_jobentry, "tablename");
long id_db = rep.getJobEntryAttributeInteger(id_jobentry, "id_database");
if (id_db>0)
{
connection = Const.findDatabase(databases, id_db);
}
else
{
// This is were we end up in normally, the previous lines are for backward compatibility.
connection = Const.findDatabase(databases, rep.getJobEntryAttributeString(id_jobentry, "connection"));
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load job entry of type table exists from the repository for id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "tablename", tablename);
if (connection!=null) rep.saveJobEntryAttribute(id_job, getID(), "connection", connection.getName());
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("unable to save jobentry of type 'table exists' to the repository for id_job="+id_job, dbe);
}
}
public void setTablename(String tablename)
{
this.tablename = tablename;
}
public String getTablename()
{
return tablename;
}
public void setDatabase(DatabaseMeta database)
{
this.connection = database;
}
public DatabaseMeta getDatabase()
{
return connection;
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return false;
}
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = new Result(nr);
result.setResult(false);
if (connection!=null)
{
Database db = new Database(connection);
try
{
db.connect();
String realTablename = StringUtil.environmentSubstitute(tablename);
- if (db.checkTableExists(tablename))
+ if (db.checkTableExists(realTablename))
{
log.logDetailed(toString(), "Table ["+realTablename+"] exists.");
result.setResult(true);
}
else
{
log.logDetailed(toString(), "Table ["+realTablename+"] doesn't exist!");
}
db.disconnect();
}
catch(KettleDatabaseException dbe)
{
result.setNrErrors(1);
log.logError(toString(), "An error occurred executing this step: "+dbe.getMessage());
}
}
else
{
result.setNrErrors(1);
log.logError(toString(), "No database connection is defined.");
}
return result;
}
public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) {
return new JobEntryTableExistsDialog(shell,this,jobMeta);
}
public DatabaseMeta[] getUsedDatabaseConnections()
{
return new DatabaseMeta[] { connection, };
}
}
| true | true | public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = new Result(nr);
result.setResult(false);
if (connection!=null)
{
Database db = new Database(connection);
try
{
db.connect();
String realTablename = StringUtil.environmentSubstitute(tablename);
if (db.checkTableExists(tablename))
{
log.logDetailed(toString(), "Table ["+realTablename+"] exists.");
result.setResult(true);
}
else
{
log.logDetailed(toString(), "Table ["+realTablename+"] doesn't exist!");
}
db.disconnect();
}
catch(KettleDatabaseException dbe)
{
result.setNrErrors(1);
log.logError(toString(), "An error occurred executing this step: "+dbe.getMessage());
}
}
else
{
result.setNrErrors(1);
log.logError(toString(), "No database connection is defined.");
}
return result;
}
| public Result execute(Result prev_result, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = new Result(nr);
result.setResult(false);
if (connection!=null)
{
Database db = new Database(connection);
try
{
db.connect();
String realTablename = StringUtil.environmentSubstitute(tablename);
if (db.checkTableExists(realTablename))
{
log.logDetailed(toString(), "Table ["+realTablename+"] exists.");
result.setResult(true);
}
else
{
log.logDetailed(toString(), "Table ["+realTablename+"] doesn't exist!");
}
db.disconnect();
}
catch(KettleDatabaseException dbe)
{
result.setNrErrors(1);
log.logError(toString(), "An error occurred executing this step: "+dbe.getMessage());
}
}
else
{
result.setNrErrors(1);
log.logError(toString(), "No database connection is defined.");
}
return result;
}
|
diff --git a/src/org/eclipse/jface/util/OpenStrategy.java b/src/org/eclipse/jface/util/OpenStrategy.java
index b3744050..11212aa5 100644
--- a/src/org/eclipse/jface/util/OpenStrategy.java
+++ b/src/org/eclipse/jface/util/OpenStrategy.java
@@ -1,387 +1,388 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableTree;
import org.eclipse.swt.custom.TableTreeItem;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.*;
/**
* Implementation of single-click and double-click strategies.
* <p>
* Usage:
* <pre>
* OpenStrategy handler = new OpenStrategy(control);
* handler.addOpenListener(new IOpenEventListener() {
* public void handleOpen(SelectionEvent e) {
* ... // code to handle the open event.
* }
* });
* </pre>
* </p>
*/
public class OpenStrategy {
/**
* Default behavior. Double click to open the item.
*/
public static final int DOUBLE_CLICK = 0;
/**
* Single click will open the item.
*/
public static final int SINGLE_CLICK = 1;
/**
* Hover will select the item.
*/
public static final int SELECT_ON_HOVER = 1 << 1;
/**
* Open item when using arrow keys
*/
public static final int ARROW_KEYS_OPEN = 1 << 2;
/** A single click will generate
* an open event but key arrows will not do anything.
*
* @deprecated
*/
public static final int NO_TIMER = SINGLE_CLICK;
/** A single click will generate an open
* event and key arrows will generate an open event after a
* small time.
*
* @deprecated
*/
public static final int FILE_EXPLORER = SINGLE_CLICK | ARROW_KEYS_OPEN;
/** Pointing to an item will change the selection
* and a single click will gererate an open event
*
* @deprecated
*/
public static final int ACTIVE_DESKTOP = SINGLE_CLICK | SELECT_ON_HOVER;
// Time used in FILE_EXPLORER and ACTIVE_DESKTOP
private static final int TIME = 500;
/* SINGLE_CLICK or DOUBLE_CLICK;
* In case of SINGLE_CLICK, the bits SELECT_ON_HOVER and ARROW_KEYS_OPEN
* my be set as well. */
private static int CURRENT_METHOD = DOUBLE_CLICK;
private Listener eventHandler;
private ListenerList openEventListeners = new ListenerList(1);
private ListenerList selectionEventListeners = new ListenerList(1);
private ListenerList postSelectionEventListeners = new ListenerList(1);
public OpenStrategy(Control control) {
initializeHandler(control.getDisplay());
addListener(control);
}
/**
* Adds an IOpenEventListener to the collection of openEventListeners
*/
public void addOpenListener(IOpenEventListener listener) {
openEventListeners.add(listener);
}
/**
* Removes an IOpenEventListener to the collection of openEventListeners
*/
public void removeOpenListener(IOpenEventListener listener) {
openEventListeners.remove(listener);
}
/**
* Adds an SelectionListener to the collection of selectionEventListeners
*/
public void addSelectionListener(SelectionListener listener) {
selectionEventListeners.add(listener);
}
/**
* Removes an SelectionListener to the collection of selectionEventListeners
*/
public void removeSelectionListener(SelectionListener listener) {
selectionEventListeners.remove(listener);
}
/**
* Adds an SelectionListener to the collection of selectionEventListeners
*/
public void addPostSelectionListener(SelectionListener listener) {
postSelectionEventListeners.add(listener);
}
/**
* Removes an SelectionListener to the collection of selectionEventListeners
*/
public void removePostSelectionListener(SelectionListener listener) {
postSelectionEventListeners.remove(listener);
}
/**
* Returns the current used single/double-click method
*
* This method is internal to the framework; it should not be implemented outside
* the framework.
*/
public static int getOpenMethod() {
return CURRENT_METHOD;
}
/**
* Set the current used single/double-click method.
*
* This method is internal to the framework; it should not be implemented outside
* the framework.
*/
public static void setOpenMethod(int method) {
if(method == DOUBLE_CLICK) {
CURRENT_METHOD = method;
return;
}
if((method & SINGLE_CLICK) == 0)
throw new IllegalArgumentException("Invalid open mode"); //$NON-NLS-1$
if((method & (SINGLE_CLICK | SELECT_ON_HOVER | ARROW_KEYS_OPEN)) == 0)
throw new IllegalArgumentException("Invalid open mode"); //$NON-NLS-1$
CURRENT_METHOD = method;
}
/**
* Return true if editors should be activated when opened.
*/
public static boolean activateOnOpen() {
return getOpenMethod() == DOUBLE_CLICK;
}
/*
* Adds all needed listener to the control in order to implement
* single-click/double-click strategies.
*/
private void addListener(Control c) {
c.addListener(SWT.MouseEnter,eventHandler);
c.addListener(SWT.MouseExit,eventHandler);
c.addListener(SWT.MouseMove,eventHandler);
c.addListener(SWT.MouseDown, eventHandler);
c.addListener(SWT.MouseUp, eventHandler);
c.addListener(SWT.KeyDown, eventHandler);
c.addListener(SWT.Selection, eventHandler);
c.addListener(SWT.DefaultSelection, eventHandler);
}
/*
* Fire the selection event to all selectionEventListeners
*/
private void fireSelectionEvent(SelectionEvent e) {
if(e.item != null && e.item.isDisposed())
return;
Object l[] = selectionEventListeners.getListeners();
for (int i = 0; i < l.length; i++) {
((SelectionListener)l[i]).widgetSelected(e);
}
}
/*
* Fire the default selection event to all selectionEventListeners
*/
private void fireDefaultSelectionEvent(SelectionEvent e) {
Object l[] = selectionEventListeners.getListeners();
for (int i = 0; i < l.length; i++) {
((SelectionListener)l[i]).widgetDefaultSelected(e);
}
}
/*
* Fire the post selection event to all postSelectionEventListeners
*/
private void firePostSelectionEvent(SelectionEvent e) {
if(e.item != null && e.item.isDisposed())
return;
Object l[] = postSelectionEventListeners.getListeners();
for (int i = 0; i < l.length; i++) {
((SelectionListener)l[i]).widgetSelected(e);
}
}
/*
* Fire the open event to all openEventListeners
*/
private void fireOpenEvent(SelectionEvent e) {
if(e.item != null && e.item.isDisposed())
return;
Object l[] = openEventListeners.getListeners();
for (int i = 0; i < l.length; i++) {
((IOpenEventListener)l[i]).handleOpen(e);
}
}
//Initialize event handler.
private void initializeHandler(final Display display) {
eventHandler = new Listener() {
boolean timerStarted = false;
Event mouseUpEvent = null;
Event mouseMoveEvent = null;
SelectionEvent selectionPendent = null;
boolean enterKeyDown = false;
SelectionEvent defaultSelectionPendent = null;
boolean arrowKeyDown = false;
final int[] count = new int[1];
long startTime = System.currentTimeMillis();
public void handleEvent(final Event e) {
if(e.type == SWT.DefaultSelection) {
SelectionEvent event = new SelectionEvent(e);
fireDefaultSelectionEvent(event);
if(CURRENT_METHOD == DOUBLE_CLICK) {
fireOpenEvent(event);
} else {
if(enterKeyDown) {
fireOpenEvent(event);
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
defaultSelectionPendent = event;
}
}
return;
}
switch (e.type) {
case SWT.MouseEnter:
case SWT.MouseExit:
mouseUpEvent = null;
mouseMoveEvent = null;
selectionPendent = null;
break;
case SWT.MouseMove:
if((CURRENT_METHOD & SELECT_ON_HOVER) == 0)
return;
if(e.stateMask != 0)
return;
if(e.widget.getDisplay().getFocusControl() != e.widget)
return;
mouseMoveEvent = e;
final Runnable runnable[] = new Runnable[1];
runnable[0] = new Runnable() {
public void run() {
long time = System.currentTimeMillis();
int diff = (int)(time - startTime);
if(diff <= TIME) {
display.timerExec(diff * 2 / 3,runnable[0]);
} else {
timerStarted = false;
setSelection(mouseMoveEvent);
}
}
};
startTime = System.currentTimeMillis();
if(!timerStarted) {
timerStarted = true;
display.timerExec(TIME * 2 / 3,runnable[0]);
}
break;
case SWT.MouseDown :
+ mouseUpEvent = null;
arrowKeyDown = false;
break;
case SWT.MouseUp:
mouseMoveEvent = null;
if((e.button != 1) || ((e.stateMask & ~SWT.BUTTON1) != 0))
return;
if(selectionPendent != null)
mouseSelectItem(selectionPendent);
else
mouseUpEvent = e;
break;
case SWT.KeyDown:
mouseMoveEvent = null;
mouseUpEvent = null;
arrowKeyDown = ((e.keyCode == SWT.ARROW_UP) || (e.keyCode == SWT.ARROW_DOWN)) && e.stateMask == 0;
if(e.character == SWT.CR) {
if(defaultSelectionPendent != null) {
fireOpenEvent(new SelectionEvent(e));
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
enterKeyDown = true;
}
}
break;
case SWT.Selection:
SelectionEvent event = new SelectionEvent(e);
fireSelectionEvent(event);
mouseMoveEvent = null;
if (mouseUpEvent != null)
mouseSelectItem(event);
else
selectionPendent = event;
count[0]++;
// In the case of arrowUp/arrowDown when in the arrowKeysOpen mode, we
// want to delay any selection until the last arrowDown/Up occurs. This
// handles the case where the user presses arrowDown/Up successively.
// We only want to open an editor for the last selected item.
display.asyncExec(new Runnable() {
public void run() {
if (arrowKeyDown) {
display.timerExec(TIME, new Runnable() {
int id = count[0];
public void run() {
if (id == count[0]) {
firePostSelectionEvent(new SelectionEvent(e));
if((CURRENT_METHOD & ARROW_KEYS_OPEN) != 0)
fireOpenEvent(new SelectionEvent(e));
}
}
});
} else {
firePostSelectionEvent(new SelectionEvent(e));
}
}
});
break;
}
}
void mouseSelectItem(SelectionEvent e) {
if((CURRENT_METHOD & SINGLE_CLICK) != 0)
fireOpenEvent(e);
mouseUpEvent = null;
selectionPendent = null;
}
void setSelection(Event e) {
if(e == null)
return;
Widget w = e.widget;
if(w.isDisposed())
return;
SelectionEvent selEvent = new SelectionEvent(e);
/*ISSUE: May have to create a interface with method:
setSelection(Point p) so that user's custom widgets
can use this class. If we keep this option. */
if(w instanceof Tree) {
Tree tree = (Tree)w;
TreeItem item = tree.getItem(new Point(e.x,e.y));
if(item != null)
tree.setSelection(new TreeItem[]{item});
selEvent.item = item;
} else if(w instanceof Table) {
Table table = (Table)w;
TableItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableItem[]{item});
selEvent.item = item;
} else if(w instanceof TableTree) {
TableTree table = (TableTree)w;
TableTreeItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableTreeItem[]{item});
selEvent.item = item;
} else {
return;
}
if(selEvent.item == null)
return;
fireSelectionEvent(selEvent);
firePostSelectionEvent(selEvent);
}
};
}
}
| true | true | private void initializeHandler(final Display display) {
eventHandler = new Listener() {
boolean timerStarted = false;
Event mouseUpEvent = null;
Event mouseMoveEvent = null;
SelectionEvent selectionPendent = null;
boolean enterKeyDown = false;
SelectionEvent defaultSelectionPendent = null;
boolean arrowKeyDown = false;
final int[] count = new int[1];
long startTime = System.currentTimeMillis();
public void handleEvent(final Event e) {
if(e.type == SWT.DefaultSelection) {
SelectionEvent event = new SelectionEvent(e);
fireDefaultSelectionEvent(event);
if(CURRENT_METHOD == DOUBLE_CLICK) {
fireOpenEvent(event);
} else {
if(enterKeyDown) {
fireOpenEvent(event);
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
defaultSelectionPendent = event;
}
}
return;
}
switch (e.type) {
case SWT.MouseEnter:
case SWT.MouseExit:
mouseUpEvent = null;
mouseMoveEvent = null;
selectionPendent = null;
break;
case SWT.MouseMove:
if((CURRENT_METHOD & SELECT_ON_HOVER) == 0)
return;
if(e.stateMask != 0)
return;
if(e.widget.getDisplay().getFocusControl() != e.widget)
return;
mouseMoveEvent = e;
final Runnable runnable[] = new Runnable[1];
runnable[0] = new Runnable() {
public void run() {
long time = System.currentTimeMillis();
int diff = (int)(time - startTime);
if(diff <= TIME) {
display.timerExec(diff * 2 / 3,runnable[0]);
} else {
timerStarted = false;
setSelection(mouseMoveEvent);
}
}
};
startTime = System.currentTimeMillis();
if(!timerStarted) {
timerStarted = true;
display.timerExec(TIME * 2 / 3,runnable[0]);
}
break;
case SWT.MouseDown :
arrowKeyDown = false;
break;
case SWT.MouseUp:
mouseMoveEvent = null;
if((e.button != 1) || ((e.stateMask & ~SWT.BUTTON1) != 0))
return;
if(selectionPendent != null)
mouseSelectItem(selectionPendent);
else
mouseUpEvent = e;
break;
case SWT.KeyDown:
mouseMoveEvent = null;
mouseUpEvent = null;
arrowKeyDown = ((e.keyCode == SWT.ARROW_UP) || (e.keyCode == SWT.ARROW_DOWN)) && e.stateMask == 0;
if(e.character == SWT.CR) {
if(defaultSelectionPendent != null) {
fireOpenEvent(new SelectionEvent(e));
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
enterKeyDown = true;
}
}
break;
case SWT.Selection:
SelectionEvent event = new SelectionEvent(e);
fireSelectionEvent(event);
mouseMoveEvent = null;
if (mouseUpEvent != null)
mouseSelectItem(event);
else
selectionPendent = event;
count[0]++;
// In the case of arrowUp/arrowDown when in the arrowKeysOpen mode, we
// want to delay any selection until the last arrowDown/Up occurs. This
// handles the case where the user presses arrowDown/Up successively.
// We only want to open an editor for the last selected item.
display.asyncExec(new Runnable() {
public void run() {
if (arrowKeyDown) {
display.timerExec(TIME, new Runnable() {
int id = count[0];
public void run() {
if (id == count[0]) {
firePostSelectionEvent(new SelectionEvent(e));
if((CURRENT_METHOD & ARROW_KEYS_OPEN) != 0)
fireOpenEvent(new SelectionEvent(e));
}
}
});
} else {
firePostSelectionEvent(new SelectionEvent(e));
}
}
});
break;
}
}
void mouseSelectItem(SelectionEvent e) {
if((CURRENT_METHOD & SINGLE_CLICK) != 0)
fireOpenEvent(e);
mouseUpEvent = null;
selectionPendent = null;
}
void setSelection(Event e) {
if(e == null)
return;
Widget w = e.widget;
if(w.isDisposed())
return;
SelectionEvent selEvent = new SelectionEvent(e);
/*ISSUE: May have to create a interface with method:
setSelection(Point p) so that user's custom widgets
can use this class. If we keep this option. */
if(w instanceof Tree) {
Tree tree = (Tree)w;
TreeItem item = tree.getItem(new Point(e.x,e.y));
if(item != null)
tree.setSelection(new TreeItem[]{item});
selEvent.item = item;
} else if(w instanceof Table) {
Table table = (Table)w;
TableItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableItem[]{item});
selEvent.item = item;
} else if(w instanceof TableTree) {
TableTree table = (TableTree)w;
TableTreeItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableTreeItem[]{item});
selEvent.item = item;
} else {
return;
}
if(selEvent.item == null)
return;
fireSelectionEvent(selEvent);
firePostSelectionEvent(selEvent);
}
};
}
| private void initializeHandler(final Display display) {
eventHandler = new Listener() {
boolean timerStarted = false;
Event mouseUpEvent = null;
Event mouseMoveEvent = null;
SelectionEvent selectionPendent = null;
boolean enterKeyDown = false;
SelectionEvent defaultSelectionPendent = null;
boolean arrowKeyDown = false;
final int[] count = new int[1];
long startTime = System.currentTimeMillis();
public void handleEvent(final Event e) {
if(e.type == SWT.DefaultSelection) {
SelectionEvent event = new SelectionEvent(e);
fireDefaultSelectionEvent(event);
if(CURRENT_METHOD == DOUBLE_CLICK) {
fireOpenEvent(event);
} else {
if(enterKeyDown) {
fireOpenEvent(event);
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
defaultSelectionPendent = event;
}
}
return;
}
switch (e.type) {
case SWT.MouseEnter:
case SWT.MouseExit:
mouseUpEvent = null;
mouseMoveEvent = null;
selectionPendent = null;
break;
case SWT.MouseMove:
if((CURRENT_METHOD & SELECT_ON_HOVER) == 0)
return;
if(e.stateMask != 0)
return;
if(e.widget.getDisplay().getFocusControl() != e.widget)
return;
mouseMoveEvent = e;
final Runnable runnable[] = new Runnable[1];
runnable[0] = new Runnable() {
public void run() {
long time = System.currentTimeMillis();
int diff = (int)(time - startTime);
if(diff <= TIME) {
display.timerExec(diff * 2 / 3,runnable[0]);
} else {
timerStarted = false;
setSelection(mouseMoveEvent);
}
}
};
startTime = System.currentTimeMillis();
if(!timerStarted) {
timerStarted = true;
display.timerExec(TIME * 2 / 3,runnable[0]);
}
break;
case SWT.MouseDown :
mouseUpEvent = null;
arrowKeyDown = false;
break;
case SWT.MouseUp:
mouseMoveEvent = null;
if((e.button != 1) || ((e.stateMask & ~SWT.BUTTON1) != 0))
return;
if(selectionPendent != null)
mouseSelectItem(selectionPendent);
else
mouseUpEvent = e;
break;
case SWT.KeyDown:
mouseMoveEvent = null;
mouseUpEvent = null;
arrowKeyDown = ((e.keyCode == SWT.ARROW_UP) || (e.keyCode == SWT.ARROW_DOWN)) && e.stateMask == 0;
if(e.character == SWT.CR) {
if(defaultSelectionPendent != null) {
fireOpenEvent(new SelectionEvent(e));
enterKeyDown = false;
defaultSelectionPendent = null;
} else {
enterKeyDown = true;
}
}
break;
case SWT.Selection:
SelectionEvent event = new SelectionEvent(e);
fireSelectionEvent(event);
mouseMoveEvent = null;
if (mouseUpEvent != null)
mouseSelectItem(event);
else
selectionPendent = event;
count[0]++;
// In the case of arrowUp/arrowDown when in the arrowKeysOpen mode, we
// want to delay any selection until the last arrowDown/Up occurs. This
// handles the case where the user presses arrowDown/Up successively.
// We only want to open an editor for the last selected item.
display.asyncExec(new Runnable() {
public void run() {
if (arrowKeyDown) {
display.timerExec(TIME, new Runnable() {
int id = count[0];
public void run() {
if (id == count[0]) {
firePostSelectionEvent(new SelectionEvent(e));
if((CURRENT_METHOD & ARROW_KEYS_OPEN) != 0)
fireOpenEvent(new SelectionEvent(e));
}
}
});
} else {
firePostSelectionEvent(new SelectionEvent(e));
}
}
});
break;
}
}
void mouseSelectItem(SelectionEvent e) {
if((CURRENT_METHOD & SINGLE_CLICK) != 0)
fireOpenEvent(e);
mouseUpEvent = null;
selectionPendent = null;
}
void setSelection(Event e) {
if(e == null)
return;
Widget w = e.widget;
if(w.isDisposed())
return;
SelectionEvent selEvent = new SelectionEvent(e);
/*ISSUE: May have to create a interface with method:
setSelection(Point p) so that user's custom widgets
can use this class. If we keep this option. */
if(w instanceof Tree) {
Tree tree = (Tree)w;
TreeItem item = tree.getItem(new Point(e.x,e.y));
if(item != null)
tree.setSelection(new TreeItem[]{item});
selEvent.item = item;
} else if(w instanceof Table) {
Table table = (Table)w;
TableItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableItem[]{item});
selEvent.item = item;
} else if(w instanceof TableTree) {
TableTree table = (TableTree)w;
TableTreeItem item = table.getItem(new Point(e.x,e.y));
if(item != null)
table.setSelection(new TableTreeItem[]{item});
selEvent.item = item;
} else {
return;
}
if(selEvent.item == null)
return;
fireSelectionEvent(selEvent);
firePostSelectionEvent(selEvent);
}
};
}
|
diff --git a/src/plugins/KeyUtils/toadlets/StaticToadlet.java b/src/plugins/KeyUtils/toadlets/StaticToadlet.java
index b5da218..884b52c 100644
--- a/src/plugins/KeyUtils/toadlets/StaticToadlet.java
+++ b/src/plugins/KeyUtils/toadlets/StaticToadlet.java
@@ -1,107 +1,107 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.KeyUtils.toadlets;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.Date;
import freenet.client.DefaultMIMETypes;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.l10n.PluginL10n;
import freenet.support.Logger;
import freenet.support.api.Bucket;
import freenet.support.api.HTTPRequest;
import freenet.support.plugins.helpers1.InvisibleWebInterfaceToadlet;
import freenet.support.plugins.helpers1.PluginContext;
/**
* @author saces
*
*/
public class StaticToadlet extends InvisibleWebInterfaceToadlet {
private static volatile boolean logDEBUG;
static {
Logger.registerClass(StaticToadlet.class);
}
/** The path used as prefix when loading resources. */
private final String resourcePathPrefix;
/** The MIME type for the files this path contains. */
private final String mimeType;
private final PluginL10n _intl;
public StaticToadlet(PluginContext context, String pluginUri, String path, String rezPath, String mime, PluginL10n intl) {
super(context, pluginUri, path, null);
resourcePathPrefix = rezPath;
mimeType = mime;
_intl = intl;
}
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
String path = normalizePath(request.getPath());
- if (logDEBUG) Logger.debug(this, "Requested ressource: "+path);
+ if (logDEBUG) Logger.debug(this, "Requested ressource: "+path+" ("+uri+')');
int lastSlash = path.lastIndexOf('/');
String filename = path.substring(lastSlash + 1);
String fn = resourcePathPrefix + filename;
- if (logDEBUG) Logger.debug(this, "Resolved ressource path: "+path);
+ if (logDEBUG) Logger.debug(this, "Resolved ressource path: "+fn);
InputStream fileInputStream = getClass().getResourceAsStream(fn);
if (fileInputStream == null) {
if (logDEBUG) Logger.debug(this, "Ressource not found.");
ctx.sendReplyHeaders(404, "Not found.", null, null, 0);
return;
}
Bucket data = ctx.getBucketFactory().makeBucket(fileInputStream.available());
OutputStream os = data.getOutputStream();
byte[] cbuf = new byte[4096];
while(true) {
int r = fileInputStream.read(cbuf);
if(r == -1) break;
os.write(cbuf, 0, r);
}
fileInputStream.close();
os.close();
URL url = getClass().getResource(resourcePathPrefix+path);
Date mTime = getUrlMTime(url);
String mime = (mimeType != null) ? (mimeType) : (DefaultMIMETypes.guessMIMEType(path, false));
ctx.sendReplyHeaders(200, "OK", null, mime, data.size(), mTime);
ctx.writeData(data);
}
/**
* Try to find the modification time for a URL, or return null if not possible
* We usually load our resources from the JAR, or possibly from a file in some setups, so we check the modification time of
* the JAR for resources in a jar and the mtime for files.
*/
private Date getUrlMTime(URL url) {
if (url.getProtocol().equals("jar")) {
File f = new File(url.getPath().substring(0, url.getPath().indexOf('!')));
return new Date(f.lastModified());
} else if (url.getProtocol().equals("file")) {
File f = new File(url.getPath());
return new Date(f.lastModified());
} else {
return null;
}
}
private String i18n(String key) {
return _intl.getBase().getString(key);
}
}
| false | true | public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
String path = normalizePath(request.getPath());
if (logDEBUG) Logger.debug(this, "Requested ressource: "+path);
int lastSlash = path.lastIndexOf('/');
String filename = path.substring(lastSlash + 1);
String fn = resourcePathPrefix + filename;
if (logDEBUG) Logger.debug(this, "Resolved ressource path: "+path);
InputStream fileInputStream = getClass().getResourceAsStream(fn);
if (fileInputStream == null) {
if (logDEBUG) Logger.debug(this, "Ressource not found.");
ctx.sendReplyHeaders(404, "Not found.", null, null, 0);
return;
}
Bucket data = ctx.getBucketFactory().makeBucket(fileInputStream.available());
OutputStream os = data.getOutputStream();
byte[] cbuf = new byte[4096];
while(true) {
int r = fileInputStream.read(cbuf);
if(r == -1) break;
os.write(cbuf, 0, r);
}
fileInputStream.close();
os.close();
URL url = getClass().getResource(resourcePathPrefix+path);
Date mTime = getUrlMTime(url);
String mime = (mimeType != null) ? (mimeType) : (DefaultMIMETypes.guessMIMEType(path, false));
ctx.sendReplyHeaders(200, "OK", null, mime, data.size(), mTime);
ctx.writeData(data);
}
| public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
String path = normalizePath(request.getPath());
if (logDEBUG) Logger.debug(this, "Requested ressource: "+path+" ("+uri+')');
int lastSlash = path.lastIndexOf('/');
String filename = path.substring(lastSlash + 1);
String fn = resourcePathPrefix + filename;
if (logDEBUG) Logger.debug(this, "Resolved ressource path: "+fn);
InputStream fileInputStream = getClass().getResourceAsStream(fn);
if (fileInputStream == null) {
if (logDEBUG) Logger.debug(this, "Ressource not found.");
ctx.sendReplyHeaders(404, "Not found.", null, null, 0);
return;
}
Bucket data = ctx.getBucketFactory().makeBucket(fileInputStream.available());
OutputStream os = data.getOutputStream();
byte[] cbuf = new byte[4096];
while(true) {
int r = fileInputStream.read(cbuf);
if(r == -1) break;
os.write(cbuf, 0, r);
}
fileInputStream.close();
os.close();
URL url = getClass().getResource(resourcePathPrefix+path);
Date mTime = getUrlMTime(url);
String mime = (mimeType != null) ? (mimeType) : (DefaultMIMETypes.guessMIMEType(path, false));
ctx.sendReplyHeaders(200, "OK", null, mime, data.size(), mTime);
ctx.writeData(data);
}
|
diff --git a/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/AbstractCheckVisitor.java b/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/AbstractCheckVisitor.java
index 368c8521f..6e45e0988 100644
--- a/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/AbstractCheckVisitor.java
+++ b/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/AbstractCheckVisitor.java
@@ -1,115 +1,115 @@
//Tested with BCEL-5.1
//http://jakarta.apache.org/builds/jakarta-bcel/release/v5.1/
package com.puppycrawl.tools.checkstyle.bcel;
import java.util.Set;
import com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessages;
/**
* Abstract class for checks with visitors.
* @author Rick Giles
*/
//TODO: Refactor with class Check
public abstract class AbstractCheckVisitor
extends AbstractViolationReporter
implements IObjectSetVisitor
{
/** the object for collecting messages. */
private LocalizedMessages mMessages;
/** @see com.puppycrawl.tools.checkstyle.bcel.IParserCheck */
public org.apache.bcel.classfile.Visitor getClassFileVisitor()
{
return new EmptyClassFileVisitor();
}
/**
* @see com.puppycrawl.tools.checkstyle.bcel.IParserCheck
*/
public org.apache.bcel.generic.Visitor getGenericVisitor()
{
return new EmptyGenericVisitor();
}
/**
* Initialse the check. This is the time to verify that the check has
* everything required to perform it job.
*/
public void init()
{
}
/**
* Destroy the check. It is being retired from service.
*/
public void destroy()
{
}
/**
* Set the global object used to collect messages.
* @param aMessages the messages to log with
*/
public final void setMessages(LocalizedMessages aMessages)
{
mMessages = aMessages;
}
/**
* Log an error message.
*
* @param aLine the line number where the error was found
* @param aKey the message that describes the error
* @param aArgs the details of the message
*
* @see java.text.MessageFormat
*/
protected final void log(int aLine, String aKey, Object aArgs[])
{
mMessages.add(
new LocalizedMessage(
aLine,
getMessageBundle(),
aKey,
aArgs,
getSeverityLevel(),
- this.getClass().getName()));
+ this.getClass()));
}
/**
* @see com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
*/
protected void log(int aLine, int aCol, String aKey, Object[] aArgs)
{
}
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aObject)
{
}
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveObject(Object aObject)
{
}
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitSet(Set aJavaClassDefs)
{
}
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClassDefs)
{
}
/**
* Gets the deep BCEL visitor.
* @return the deep BCEL visitor for this check.
*/
public abstract IDeepVisitor getVisitor();
}
| true | true | protected final void log(int aLine, String aKey, Object aArgs[])
{
mMessages.add(
new LocalizedMessage(
aLine,
getMessageBundle(),
aKey,
aArgs,
getSeverityLevel(),
this.getClass().getName()));
}
| protected final void log(int aLine, String aKey, Object aArgs[])
{
mMessages.add(
new LocalizedMessage(
aLine,
getMessageBundle(),
aKey,
aArgs,
getSeverityLevel(),
this.getClass()));
}
|
diff --git a/src/org/openstreetmap/josm/gui/dialogs/PropertiesDialog.java b/src/org/openstreetmap/josm/gui/dialogs/PropertiesDialog.java
index 55c66fa1..0930b210 100644
--- a/src/org/openstreetmap/josm/gui/dialogs/PropertiesDialog.java
+++ b/src/org/openstreetmap/josm/gui/dialogs/PropertiesDialog.java
@@ -1,894 +1,892 @@
// License: GPL. See LICENSE file for details.
package org.openstreetmap.josm.gui.dialogs;
import static org.openstreetmap.josm.tools.I18n.marktr;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.openstreetmap.josm.tools.I18n.trn;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.Map.Entry;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.command.ChangeCommand;
import org.openstreetmap.josm.command.ChangePropertyCommand;
import org.openstreetmap.josm.command.Command;
import org.openstreetmap.josm.command.SequenceCommand;
import org.openstreetmap.josm.data.SelectionChangedListener;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.data.osm.RelationMember;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.gui.DefaultNameFormatter;
import org.openstreetmap.josm.gui.ExtendedDialog;
import org.openstreetmap.josm.gui.MapFrame;
import org.openstreetmap.josm.gui.SideButton;
import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.gui.layer.OsmDataLayer;
import org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener;
import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
import org.openstreetmap.josm.gui.tagging.TaggingPreset;
import org.openstreetmap.josm.tools.AutoCompleteComboBox;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.Shortcut;
/**
* This dialog displays the properties of the current selected primitives.
*
* If no object is selected, the dialog list is empty.
* If only one is selected, all properties of this object are selected.
* If more than one object are selected, the sum of all properties are displayed. If the
* different objects share the same property, the shared value is displayed. If they have
* different values, all of them are put in a combo box and the string "<different>"
* is displayed in italic.
*
* Below the list, the user can click on an add, modify and delete property button to
* edit the table selection value.
*
* The command is applied to all selected entries.
*
* @author imi
*/
public class PropertiesDialog extends ToggleDialog implements SelectionChangedListener, LayerChangeListener {
/**
* Watches for double clicks and from editing or new property, depending on the
* location, the click was.
* @author imi
*/
public class DblClickWatch extends MouseAdapter {
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() < 2)
{
if (e.getSource() == propertyTable) {
membershipTable.clearSelection();
} else if (e.getSource() == membershipTable) {
propertyTable.clearSelection();
}
}
else if (e.getSource() == propertyTable)
{
int row = propertyTable.rowAtPoint(e.getPoint());
if (row > -1) {
propertyEdit(row);
}
} else if (e.getSource() == membershipTable) {
int row = membershipTable.rowAtPoint(e.getPoint());
if (row > -1) {
membershipEdit(row);
}
}
else
{
add();
}
}
}
private final Map<String, Map<String, Integer>> valueCount = new TreeMap<String, Map<String, Integer>>();
/**
* Edit the value in the properties table row
* @param row The row of the table from which the value is edited.
*/
@SuppressWarnings("unchecked")
void propertyEdit(int row) {
Collection<OsmPrimitive> sel = Main.main.getCurrentDataSet().getSelected();
if (sel.isEmpty()) return;
String key = propertyData.getValueAt(row, 0).toString();
objKey=key;
String msg = "<html>"+trn("This will change up to {0} object.",
"This will change up to {0} objects.", sel.size(), sel.size())
+"<br><br>("+tr("An empty value deletes the key.", key)+")</html>";
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(msg), BorderLayout.NORTH);
final TreeMap<String, TreeSet<String>> allData = createAutoCompletionInfo(true);
JPanel p = new JPanel(new GridBagLayout());
panel.add(p, BorderLayout.CENTER);
final AutoCompleteComboBox keys = new AutoCompleteComboBox();
keys.setPossibleItems(allData.keySet());
keys.setEditable(true);
keys.setSelectedItem(key);
p.add(new JLabel(tr("Key")), GBC.std());
p.add(Box.createHorizontalStrut(10), GBC.std());
p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
final AutoCompleteComboBox values = new AutoCompleteComboBox();
values.setRenderer(new DefaultListCellRenderer() {
@Override public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus){
Component c = super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
if (c instanceof JLabel) {
String str = null;
str=(String) value;
if (valueCount.containsKey(objKey)){
Map<String, Integer> m=valueCount.get(objKey);
if (m.containsKey(str)) {
str+="("+m.get(str)+")";
c.setFont(c.getFont().deriveFont(Font.ITALIC+Font.BOLD));
}
}
((JLabel)c).setText(str);
}
return c;
}
});
values.setEditable(true);
updateListData(key, allData, values);
Map<String, Integer> m=(Map<String, Integer>)propertyData.getValueAt(row, 1);
final String selection= m.size()!=1?tr("<different>"):m.entrySet().iterator().next().getKey();
values.setSelectedItem(selection);
values.getEditor().setItem(selection);
p.add(new JLabel(tr("Value")), GBC.std());
p.add(Box.createHorizontalStrut(10), GBC.std());
p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
addFocusAdapter(row, allData, keys, values);
final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
@Override public void selectInitialValue() {
values.requestFocusInWindow();
values.getEditor().selectAll();
}
};
final JDialog dlg = optionPane.createDialog(Main.parent, tr("Change values?"));
values.getEditor().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlg.setVisible(false);
optionPane.setValue(JOptionPane.OK_OPTION);
}
});
String oldValue = values.getEditor().getItem().toString();
dlg.setVisible(true);
Object answer = optionPane.getValue();
if (answer == null || answer == JOptionPane.UNINITIALIZED_VALUE ||
(answer instanceof Integer && (Integer)answer != JOptionPane.OK_OPTION)) {
values.getEditor().setItem(oldValue);
return;
}
String value = values.getEditor().getItem().toString().trim();
// is not Java 1.5
//value = java.text.Normalizer.normalize(value, java.text.Normalizer.Form.NFC);
if (value.equals("")) {
value = null; // delete the key
}
String newkey = keys.getEditor().getItem().toString().trim();
//newkey = java.text.Normalizer.normalize(newkey, java.text.Normalizer.Form.NFC);
if (newkey.equals("")) {
newkey = key;
value = null; // delete the key instead
}
if (key.equals(newkey) || value == null) {
Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
} else {
Collection<Command> commands=new Vector<Command>();
commands.add(new ChangePropertyCommand(sel, key, null));
if (value.equals(tr("<different>"))) {
HashMap<String, Vector<OsmPrimitive>> map=new HashMap<String, Vector<OsmPrimitive>>();
for (OsmPrimitive osm: sel) {
String val=osm.get(key);
if(val != null)
{
if (map.containsKey(val)) {
map.get(val).add(osm);
} else {
Vector<OsmPrimitive> v = new Vector<OsmPrimitive>();
v.add(osm);
map.put(val, v);
}
}
}
for (Entry<String, Vector<OsmPrimitive>> e: map.entrySet()) {
commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
}
} else {
commands.add(new ChangePropertyCommand(sel, newkey, value));
}
Main.main.undoRedo.add(new SequenceCommand(
trn("Change properties of up to {0} object",
"Change properties of up to {0} objects", sel.size(), sel.size()),
commands));
}
DataSet.fireSelectionChanged(sel);
selectionChanged(sel); // update whole table
Main.parent.repaint(); // repaint all - drawing could have been changed
if(!key.equals(newkey)) {
for(int i=0; i < propertyTable.getRowCount(); i++)
if(propertyData.getValueAt(i, 0).toString() == newkey) {
row=i;
break;
}
}
propertyTable.changeSelection(row, 0, false, false);
}
/**
* @param key
* @param allData
* @param values
*/
private void updateListData(String key, final TreeMap<String, TreeSet<String>> allData,
final AutoCompleteComboBox values) {
Collection<String> newItems;
if (allData.containsKey(key)) {
newItems = allData.get(key);
} else {
newItems = Collections.emptyList();
}
values.setPossibleItems(newItems);
}
/**
* This simply fires up an relation editor for the relation shown; everything else
* is the editor's business.
*
* @param row
*/
void membershipEdit(int row) {
Relation relation = (Relation)membershipData.getValueAt(row, 0);
Main.main.map.relationListDialog.selectRelation(relation);
RelationEditor.getEditor(
Main.map.mapView.getEditLayer(),
relation,
(Collection<RelationMember>) membershipData.getValueAt(row, 1) ).setVisible(true);
}
/**
* Open the add selection dialog and add a new key/value to the table (and
* to the dataset, of course).
*/
void add() {
Collection<OsmPrimitive> sel = Main.main.getCurrentDataSet().getSelected();
if (sel.isEmpty()) return;
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel("<html>"+trn("This will change up to {0} object.",
"This will change up to {0} objects.", sel.size(),sel.size())
+"<br><br>"+tr("Please select a key")), BorderLayout.NORTH);
final TreeMap<String, TreeSet<String>> allData = createAutoCompletionInfo(false);
final AutoCompleteComboBox keys = new AutoCompleteComboBox();
keys.setPossibleItems(allData.keySet());
keys.setEditable(true);
p.add(keys, BorderLayout.CENTER);
JPanel p2 = new JPanel(new BorderLayout());
p.add(p2, BorderLayout.SOUTH);
p2.add(new JLabel(tr("Please select a value")), BorderLayout.NORTH);
final AutoCompleteComboBox values = new AutoCompleteComboBox();
values.setEditable(true);
p2.add(values, BorderLayout.CENTER);
addFocusAdapter(-1, allData, keys, values);
JOptionPane pane = new JOptionPane(p, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION){
@Override public void selectInitialValue() {
keys.requestFocusInWindow();
keys.getEditor().selectAll();
}
};
JDialog dialog = pane.createDialog(Main.parent, tr("Change values?"));
dialog.setVisible(true);
if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(pane.getValue()))
return;
String key = keys.getEditor().getItem().toString().trim();
String value = values.getEditor().getItem().toString().trim();
if (value.equals(""))
return;
Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, value));
DataSet.fireSelectionChanged(sel);
selectionChanged(sel); // update table
Main.parent.repaint(); // repaint all - drawing could have been changed
}
/**
* @param allData
* @param keys
* @param values
*/
private void addFocusAdapter(final int row, final TreeMap<String, TreeSet<String>> allData,
final AutoCompleteComboBox keys, final AutoCompleteComboBox values) {
// get the combo box' editor component
JTextComponent editor = (JTextComponent)values.getEditor()
.getEditorComponent();
// Refresh the values model when focus is gained
editor.addFocusListener(new FocusAdapter() {
@Override public void focusGained(FocusEvent e) {
String key = keys.getEditor().getItem().toString();
updateListData(key, allData, values);
objKey=key;
}
});
}
private String objKey;
private TreeMap<String, TreeSet<String>> createAutoCompletionInfo(
boolean edit) {
final TreeMap<String, TreeSet<String>> allData = new TreeMap<String, TreeSet<String>>();
for (OsmPrimitive osm : Main.main.getCurrentDataSet().allNonDeletedPrimitives()) {
for (String key : osm.keySet()) {
TreeSet<String> values = null;
if (allData.containsKey(key)) {
values = allData.get(key);
} else {
values = new TreeSet<String>();
allData.put(key, values);
}
values.add(osm.get(key));
}
}
if (!edit) {
for (int i = 0; i < propertyData.getRowCount(); ++i) {
allData.remove(propertyData.getValueAt(i, 0));
}
}
return allData;
}
/**
* The property data.
*/
private final DefaultTableModel propertyData = new DefaultTableModel() {
@Override public boolean isCellEditable(int row, int column) {
return false;
}
@Override public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
};
/**
* The membership data.
*/
private final DefaultTableModel membershipData = new DefaultTableModel() {
@Override public boolean isCellEditable(int row, int column) {
return false;
}
@Override public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
};
/**
* The properties list.
*/
private final JTable propertyTable = new JTable(propertyData);
private final JTable membershipTable = new JTable(membershipData);
public JComboBox taggingPresets = new JComboBox();
/**
* The Add/Edit/Delete buttons (needed to be able to disable them)
*/
private final SideButton btnAdd;
private final SideButton btnEdit;
private final SideButton btnDel;
private final JPanel presets = new JPanel(new GridBagLayout());
private final JLabel selectSth = new JLabel("<html><p>"
+ tr("Please select the objects you want to change properties for.") + "</p></html>");
/**
* Create a new PropertiesDialog
*/
public PropertiesDialog(MapFrame mapFrame) {
super(tr("Properties/Memberships"), "propertiesdialog", tr("Properties for selected objects."),
Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Properties/Memberships")), KeyEvent.VK_P,
Shortcut.GROUP_LAYER, Shortcut.SHIFT_DEFAULT), 150);
// setting up the properties table
propertyData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")});
propertyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propertyTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer(){
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
String str = null;
- switch (column) {
- case 0:
+ if (value instanceof String) {
str = (String) value;
- break;
- case 1:
- Map<String, Integer> v = (Map<String,Integer>) value;
- if (v.size()!=1) {
+ } else if (value instanceof Map) {
+ Map v = (Map) value;
+ if (v.size() != 1) {
str=tr("<different>");
c.setFont(c.getFont().deriveFont(Font.ITALIC));
} else {
- str=v.entrySet().iterator().next().getKey();
+ final Map.Entry entry = (Map.Entry) v.entrySet().iterator().next();
+ str = (String) entry.getKey();
}
- break;
}
((JLabel)c).setText(str);
}
return c;
}
});
// setting up the membership table
membershipData.setColumnIdentifiers(new String[]{tr("Member Of"),tr("Role")});
membershipTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
membershipTable.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
((JLabel)c).setText(((Relation)value).getDisplayName(DefaultNameFormatter.getInstance()));
}
return c;
}
});
membershipTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
@SuppressWarnings("unchecked")
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
Collection<RelationMember> col = (Collection<RelationMember>) value;
String text = null;
for (RelationMember r : col) {
if (text == null) {
text = r.getRole();
}
else if (!text.equals(r.getRole())) {
text = tr("<different>");
break;
}
}
((JLabel)c).setText(text);
}
return c;
}
});
// combine both tables and wrap them in a scrollPane
JPanel bothTables = new JPanel();
bothTables.setLayout(new GridBagLayout());
bothTables.add(presets, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2));
bothTables.add(selectSth, GBC.eol().fill().insets(10, 10, 10, 10));
bothTables.add(propertyTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(propertyTable, GBC.eol().fill(GBC.BOTH));
bothTables.add(membershipTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(membershipTable, GBC.eol().fill(GBC.BOTH));
DblClickWatch dblClickWatch = new DblClickWatch();
propertyTable.addMouseListener(dblClickWatch);
membershipTable.addMouseListener(dblClickWatch);
JScrollPane scrollPane = new JScrollPane(bothTables);
scrollPane.addMouseListener(dblClickWatch);
add(scrollPane, BorderLayout.CENTER);
selectSth.setPreferredSize(scrollPane.getSize());
presets.setSize(scrollPane.getSize());
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
ActionListener buttonAction = new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = membershipTable.getSelectedRow();
if (e.getActionCommand().equals("Add")) {
add();
} else if(row >= 0)
{
if (e.getActionCommand().equals("Edit")) {
membershipEdit(row);
}
}
else
{
int sel = propertyTable.getSelectedRow();
// Although we might edit/delete the wrong tag here, chances are still better
// than just displaying an error message (which always "fails").
if (e.getActionCommand().equals("Edit")) {
propertyEdit(sel >= 0 ? sel : 0);
}
}
}
};
Shortcut s = Shortcut.registerShortcut("properties:add", tr("Add Properties"), KeyEvent.VK_B,
Shortcut.GROUP_MNEMONIC);
this.btnAdd = new SideButton(marktr("Add"),"add","Properties",
tr("Add a new key/value pair to all objects"), s, buttonAction);
buttonPanel.add(this.btnAdd);
s = Shortcut.registerShortcut("properties:edit", tr("Edit Properties"), KeyEvent.VK_I,
Shortcut.GROUP_MNEMONIC);
this.btnEdit = new SideButton(marktr("Edit"),"edit","Properties",
tr("Edit the value of the selected key for all objects"), s, buttonAction);
buttonPanel.add(this.btnEdit);
// -- delete action
DeleteAction deleteAction = new DeleteAction();
this.btnDel = new SideButton(deleteAction);
membershipTable.getSelectionModel().addListSelectionListener(deleteAction);
propertyTable.getSelectionModel().addListSelectionListener(deleteAction);
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"delete"
);
getActionMap().put("delete", deleteAction);
buttonPanel.add(this.btnDel);
add(buttonPanel, BorderLayout.SOUTH);
DataSet.selListeners.add(this);
Layer.listeners.add(this);
}
@Override public void setVisible(boolean b) {
super.setVisible(b);
if (b && Main.main.getCurrentDataSet() != null) {
selectionChanged(Main.main.getCurrentDataSet().getSelected());
}
}
private void checkPresets(int nodes, int ways, int relations, int closedways)
{
/**
* Small helper class that manages the highlighting of the label on hover as well as opening
* the corresponding preset when clicked
*/
class PresetLabelML implements MouseListener {
JLabel label;
Font bold;
Font normal;
TaggingPreset tag;
PresetLabelML(JLabel lbl, TaggingPreset t) {
super();
label = lbl;
lbl.setCursor(new Cursor(Cursor.HAND_CURSOR));
normal = label.getFont();
bold = normal.deriveFont(normal.getStyle() ^ Font.BOLD);
tag = t;
}
public void mouseClicked(MouseEvent arg0) {
tag.actionPerformed(null);
}
public void mouseEntered(MouseEvent arg0) {
label.setFont(bold);
}
public void mouseExited(MouseEvent arg0) {
label.setFont(normal);
}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
}
LinkedList<TaggingPreset> p = new LinkedList<TaggingPreset>();
presets.removeAll();
int total = nodes+ways+relations+closedways;
if(total == 0) {
presets.setVisible(false);
return;
}
for(TaggingPreset t : TaggingPresetPreference.taggingPresets) {
if(t.types == null || !((relations > 0 && !t.types.contains("relation")) &&
(nodes > 0 && !t.types.contains("node")) &&
(ways+closedways > 0 && !t.types.contains("way")) &&
(closedways > 0 && !t.types.contains("closedway"))))
{
int found = 0;
for(TaggingPreset.Item i : t.data) {
if(!(i instanceof TaggingPreset.Key)) {
continue;
}
String val = ((TaggingPreset.Key)i).value;
String key = ((TaggingPreset.Key)i).key;
// we subtract 100 if not found and add 1 if found
found -= 100;
if(!valueCount.containsKey(key)) {
continue;
}
Map<String, Integer> v = valueCount.get(key);
if(v.size() == 1 && v.containsKey(val) && v.get(val) == total) {
found += 101;
}
}
if(found <= 0) {
continue;
}
JLabel lbl = new JLabel(t.getName());
lbl.addMouseListener(new PresetLabelML(lbl, t));
presets.add(lbl, GBC.eol().fill(GBC.HORIZONTAL));
}
}
if(presets.getComponentCount() > 0) {
presets.setVisible(true);
// This ensures the presets are exactly as high as needed.
int height = presets.getComponentCount() * presets.getComponent(0).getHeight();
Dimension size = new Dimension(presets.getWidth(), height);
presets.setMaximumSize(size);
presets.setMinimumSize(size);
} else {
presets.setVisible(false);
}
}
public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
if (!isVisible())
return;
if (propertyTable == null)
return; // selection changed may be received in base class constructor before init
if (propertyTable.getCellEditor() != null) {
propertyTable.getCellEditor().cancelCellEditing();
}
// re-load property data
propertyData.setRowCount(0);
int nodes = 0;
int ways = 0;
int relations = 0;
int closedways = 0;
Map<String, Integer> keyCount = new HashMap<String, Integer>();
valueCount.clear();
for (OsmPrimitive osm : newSelection) {
if(osm instanceof Node) {
++nodes;
} else if(osm instanceof Relation) {
++relations;
} else if(((Way)osm).isClosed()) {
++closedways;
} else {
++ways;
}
for (Entry<String, String> e : osm.entrySet()) {
keyCount.put(e.getKey(), keyCount.containsKey(e.getKey()) ? keyCount.get(e.getKey())+1 : 1);
if (valueCount.containsKey(e.getKey())) {
Map<String, Integer> v = valueCount.get(e.getKey());
v.put(e.getValue(), v.containsKey(e.getValue())? v.get(e.getValue())+1 : 1 );
} else {
TreeMap<String,Integer> v = new TreeMap<String, Integer>();
v.put(e.getValue(), 1);
valueCount.put(e.getKey(), v);
}
}
}
for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) {
int count=0;
for (Entry<String, Integer> e1: e.getValue().entrySet()) {
count+=e1.getValue();
}
if (count < newSelection.size()) {
e.getValue().put("", newSelection.size()-count);
}
propertyData.addRow(new Object[]{e.getKey(), e.getValue()});
}
// re-load membership data
// this is rather expensive since we have to walk through all members of all existing relationships.
// could use back references here for speed if necessary.
membershipData.setRowCount(0);
Map<Relation, Collection<RelationMember>> roles = new HashMap<Relation, Collection<RelationMember>>();
if (Main.main.getCurrentDataSet() != null) {
for (Relation r : Main.main.getCurrentDataSet().relations) {
if (!r.deleted && !r.incomplete) {
for (RelationMember m : r.getMembers()) {
if (newSelection.contains(m.getMember())) {
Collection<RelationMember> value = roles.get(r);
if (value == null) {
value = new HashSet<RelationMember>();
roles.put(r, value);
}
value.add(m);
}
}
}
}
}
for (Entry<Relation, Collection<RelationMember>> e : roles.entrySet()) {
membershipData.addRow(new Object[]{e.getKey(), e.getValue()});
}
checkPresets(nodes, ways, relations, closedways);
membershipTable.getTableHeader().setVisible(membershipData.getRowCount() > 0);
membershipTable.setVisible(membershipData.getRowCount() > 0);
boolean hasSelection = !newSelection.isEmpty();
boolean hasTags = hasSelection && propertyData.getRowCount() > 0;
boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0;
btnAdd.setEnabled(hasSelection);
btnEdit.setEnabled(hasTags || hasMemberships);
btnDel.setEnabled(hasTags || hasMemberships);
propertyTable.setVisible(hasSelection);
propertyTable.getTableHeader().setVisible(hasSelection);
selectSth.setVisible(!hasSelection);
if(hasTags) {
propertyTable.changeSelection(0, 0, false, false);
} else if(hasMemberships) {
membershipTable.changeSelection(0, 0, false, false);
}
if(propertyData.getRowCount() != 0 || membershipData.getRowCount() != 0) {
setTitle(tr("Properties: {0} / Memberships: {1}",
propertyData.getRowCount(), membershipData.getRowCount()));
} else {
setTitle(tr("Properties / Memberships"));
}
}
public void activeLayerChange(Layer oldLayer, Layer newLayer) {
if (newLayer instanceof OsmDataLayer) {
OsmDataLayer dataLayer = (OsmDataLayer)newLayer;
selectionChanged(dataLayer.data.getSelected());
} else {
List<OsmPrimitive> selection = Collections.emptyList();
selectionChanged(selection);
}
}
public void layerAdded(Layer newLayer) {
// do nothing
}
public void layerRemoved(Layer oldLayer) {
// do nothing
}
class DeleteAction extends AbstractAction implements ListSelectionListener {
protected void deleteProperty(int row){
String key = propertyData.getValueAt(row, 0).toString();
Collection<OsmPrimitive> sel = Main.main.getCurrentDataSet().getSelected();
Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, null));
DataSet.fireSelectionChanged(sel);
selectionChanged(sel); // update table
int rowCount = propertyTable.getRowCount();
propertyTable.changeSelection((row < rowCount ? row : (rowCount-1)), 0, false, false);
}
protected void deleteFromRelation(int row) {
Relation cur = (Relation)membershipData.getValueAt(row, 0);
int result = new ExtendedDialog(Main.parent,
tr("Change relation"),
tr("Really delete selection from relation {0}?", cur.getDisplayName(DefaultNameFormatter.getInstance())),
new String[] {tr("Delete from relation"), tr("Cancel")},
new String[] {"dialogs/delete.png", "cancel.png"}).getValue();
if(result != 1)
return;
Relation rel = new Relation(cur);
Collection<OsmPrimitive> sel = Main.main.getCurrentDataSet().getSelected();
int index = 0;
for (RelationMember rm : cur.getMembers()) {
for (OsmPrimitive osm : sel) {
if (rm.getMember() == osm)
{
rel.removeMember(index);
break;
}
}
index++;
}
Main.main.undoRedo.add(new ChangeCommand(cur, rel));
DataSet.fireSelectionChanged(sel);
selectionChanged(sel); // update whole table
}
public DeleteAction() {
putValue(NAME, tr("Delete"));
putValue(SHORT_DESCRIPTION, tr("Delete the selected key in all objects"));
putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
Shortcut s = Shortcut.registerShortcut("properties:delete", tr("Delete Properties"), KeyEvent.VK_Q,
Shortcut.GROUP_MNEMONIC);
putValue(MNEMONIC_KEY, (int) KeyEvent.getKeyText(s.getAssignedKey()).charAt(0));
updateEnabledState();
}
public void actionPerformed(ActionEvent e) {
if (propertyTable.getSelectedRowCount() >0 ) {
int row = propertyTable.getSelectedRow();
deleteProperty(row);
} else if (membershipTable.getSelectedRowCount() > 0) {
int row = membershipTable.getSelectedRow();
deleteFromRelation(row);
}
}
protected void updateEnabledState() {
setEnabled(
PropertiesDialog.this.propertyTable.getSelectedRowCount() >0
|| PropertiesDialog.this.membershipTable.getSelectedRowCount() > 0
);
}
public void valueChanged(ListSelectionEvent e) {
updateEnabledState();
}
}
}
| false | true | public PropertiesDialog(MapFrame mapFrame) {
super(tr("Properties/Memberships"), "propertiesdialog", tr("Properties for selected objects."),
Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Properties/Memberships")), KeyEvent.VK_P,
Shortcut.GROUP_LAYER, Shortcut.SHIFT_DEFAULT), 150);
// setting up the properties table
propertyData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")});
propertyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propertyTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer(){
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
String str = null;
switch (column) {
case 0:
str = (String) value;
break;
case 1:
Map<String, Integer> v = (Map<String,Integer>) value;
if (v.size()!=1) {
str=tr("<different>");
c.setFont(c.getFont().deriveFont(Font.ITALIC));
} else {
str=v.entrySet().iterator().next().getKey();
}
break;
}
((JLabel)c).setText(str);
}
return c;
}
});
// setting up the membership table
membershipData.setColumnIdentifiers(new String[]{tr("Member Of"),tr("Role")});
membershipTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
membershipTable.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
((JLabel)c).setText(((Relation)value).getDisplayName(DefaultNameFormatter.getInstance()));
}
return c;
}
});
membershipTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
@SuppressWarnings("unchecked")
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
Collection<RelationMember> col = (Collection<RelationMember>) value;
String text = null;
for (RelationMember r : col) {
if (text == null) {
text = r.getRole();
}
else if (!text.equals(r.getRole())) {
text = tr("<different>");
break;
}
}
((JLabel)c).setText(text);
}
return c;
}
});
// combine both tables and wrap them in a scrollPane
JPanel bothTables = new JPanel();
bothTables.setLayout(new GridBagLayout());
bothTables.add(presets, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2));
bothTables.add(selectSth, GBC.eol().fill().insets(10, 10, 10, 10));
bothTables.add(propertyTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(propertyTable, GBC.eol().fill(GBC.BOTH));
bothTables.add(membershipTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(membershipTable, GBC.eol().fill(GBC.BOTH));
DblClickWatch dblClickWatch = new DblClickWatch();
propertyTable.addMouseListener(dblClickWatch);
membershipTable.addMouseListener(dblClickWatch);
JScrollPane scrollPane = new JScrollPane(bothTables);
scrollPane.addMouseListener(dblClickWatch);
add(scrollPane, BorderLayout.CENTER);
selectSth.setPreferredSize(scrollPane.getSize());
presets.setSize(scrollPane.getSize());
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
ActionListener buttonAction = new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = membershipTable.getSelectedRow();
if (e.getActionCommand().equals("Add")) {
add();
} else if(row >= 0)
{
if (e.getActionCommand().equals("Edit")) {
membershipEdit(row);
}
}
else
{
int sel = propertyTable.getSelectedRow();
// Although we might edit/delete the wrong tag here, chances are still better
// than just displaying an error message (which always "fails").
if (e.getActionCommand().equals("Edit")) {
propertyEdit(sel >= 0 ? sel : 0);
}
}
}
};
Shortcut s = Shortcut.registerShortcut("properties:add", tr("Add Properties"), KeyEvent.VK_B,
Shortcut.GROUP_MNEMONIC);
this.btnAdd = new SideButton(marktr("Add"),"add","Properties",
tr("Add a new key/value pair to all objects"), s, buttonAction);
buttonPanel.add(this.btnAdd);
s = Shortcut.registerShortcut("properties:edit", tr("Edit Properties"), KeyEvent.VK_I,
Shortcut.GROUP_MNEMONIC);
this.btnEdit = new SideButton(marktr("Edit"),"edit","Properties",
tr("Edit the value of the selected key for all objects"), s, buttonAction);
buttonPanel.add(this.btnEdit);
// -- delete action
DeleteAction deleteAction = new DeleteAction();
this.btnDel = new SideButton(deleteAction);
membershipTable.getSelectionModel().addListSelectionListener(deleteAction);
propertyTable.getSelectionModel().addListSelectionListener(deleteAction);
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"delete"
);
getActionMap().put("delete", deleteAction);
buttonPanel.add(this.btnDel);
add(buttonPanel, BorderLayout.SOUTH);
DataSet.selListeners.add(this);
Layer.listeners.add(this);
}
| public PropertiesDialog(MapFrame mapFrame) {
super(tr("Properties/Memberships"), "propertiesdialog", tr("Properties for selected objects."),
Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Properties/Memberships")), KeyEvent.VK_P,
Shortcut.GROUP_LAYER, Shortcut.SHIFT_DEFAULT), 150);
// setting up the properties table
propertyData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")});
propertyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propertyTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer(){
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
String str = null;
if (value instanceof String) {
str = (String) value;
} else if (value instanceof Map) {
Map v = (Map) value;
if (v.size() != 1) {
str=tr("<different>");
c.setFont(c.getFont().deriveFont(Font.ITALIC));
} else {
final Map.Entry entry = (Map.Entry) v.entrySet().iterator().next();
str = (String) entry.getKey();
}
}
((JLabel)c).setText(str);
}
return c;
}
});
// setting up the membership table
membershipData.setColumnIdentifiers(new String[]{tr("Member Of"),tr("Role")});
membershipTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
membershipTable.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
((JLabel)c).setText(((Relation)value).getDisplayName(DefaultNameFormatter.getInstance()));
}
return c;
}
});
membershipTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
@SuppressWarnings("unchecked")
@Override public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c instanceof JLabel) {
Collection<RelationMember> col = (Collection<RelationMember>) value;
String text = null;
for (RelationMember r : col) {
if (text == null) {
text = r.getRole();
}
else if (!text.equals(r.getRole())) {
text = tr("<different>");
break;
}
}
((JLabel)c).setText(text);
}
return c;
}
});
// combine both tables and wrap them in a scrollPane
JPanel bothTables = new JPanel();
bothTables.setLayout(new GridBagLayout());
bothTables.add(presets, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2));
bothTables.add(selectSth, GBC.eol().fill().insets(10, 10, 10, 10));
bothTables.add(propertyTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(propertyTable, GBC.eol().fill(GBC.BOTH));
bothTables.add(membershipTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
bothTables.add(membershipTable, GBC.eol().fill(GBC.BOTH));
DblClickWatch dblClickWatch = new DblClickWatch();
propertyTable.addMouseListener(dblClickWatch);
membershipTable.addMouseListener(dblClickWatch);
JScrollPane scrollPane = new JScrollPane(bothTables);
scrollPane.addMouseListener(dblClickWatch);
add(scrollPane, BorderLayout.CENTER);
selectSth.setPreferredSize(scrollPane.getSize());
presets.setSize(scrollPane.getSize());
JPanel buttonPanel = new JPanel(new GridLayout(1,3));
ActionListener buttonAction = new ActionListener(){
public void actionPerformed(ActionEvent e) {
int row = membershipTable.getSelectedRow();
if (e.getActionCommand().equals("Add")) {
add();
} else if(row >= 0)
{
if (e.getActionCommand().equals("Edit")) {
membershipEdit(row);
}
}
else
{
int sel = propertyTable.getSelectedRow();
// Although we might edit/delete the wrong tag here, chances are still better
// than just displaying an error message (which always "fails").
if (e.getActionCommand().equals("Edit")) {
propertyEdit(sel >= 0 ? sel : 0);
}
}
}
};
Shortcut s = Shortcut.registerShortcut("properties:add", tr("Add Properties"), KeyEvent.VK_B,
Shortcut.GROUP_MNEMONIC);
this.btnAdd = new SideButton(marktr("Add"),"add","Properties",
tr("Add a new key/value pair to all objects"), s, buttonAction);
buttonPanel.add(this.btnAdd);
s = Shortcut.registerShortcut("properties:edit", tr("Edit Properties"), KeyEvent.VK_I,
Shortcut.GROUP_MNEMONIC);
this.btnEdit = new SideButton(marktr("Edit"),"edit","Properties",
tr("Edit the value of the selected key for all objects"), s, buttonAction);
buttonPanel.add(this.btnEdit);
// -- delete action
DeleteAction deleteAction = new DeleteAction();
this.btnDel = new SideButton(deleteAction);
membershipTable.getSelectionModel().addListSelectionListener(deleteAction);
propertyTable.getSelectionModel().addListSelectionListener(deleteAction);
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"delete"
);
getActionMap().put("delete", deleteAction);
buttonPanel.add(this.btnDel);
add(buttonPanel, BorderLayout.SOUTH);
DataSet.selListeners.add(this);
Layer.listeners.add(this);
}
|
diff --git a/src/org/proofpad/IdeWindow.java b/src/org/proofpad/IdeWindow.java
index b14d172..23124ce 100755
--- a/src/org/proofpad/IdeWindow.java
+++ b/src/org/proofpad/IdeWindow.java
@@ -1,934 +1,933 @@
package org.proofpad;
import java.util.*;
import java.util.List;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.net.URLDecoder;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.BadLocationException;
import javax.swing.undo.UndoManager;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.proofpad.PrefsWindow.FontChangeListener;
import org.proofpad.Repl.MsgType;
//import com.apple.eawt.FullScreenAdapter;
//import com.apple.eawt.AppEvent.FullScreenEvent;
//import com.apple.eawt.FullScreenUtilities;
public class IdeWindow extends JFrame {
public static final boolean OSX = System.getProperty("os.name").indexOf("Mac") != -1;
public static final boolean WIN =
System.getProperty("os.name").toLowerCase().indexOf("windows") != -1;
public static final Color transparent = new Color(1f, 1f, 1f, 0f);
static JFileChooser fc = new JFileChooser();
static {
fc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Lisp files";
}
@Override
public boolean accept(File f) {
return f.getName().endsWith(".lisp") || f.getName().endsWith(".lsp")
|| f.getName().endsWith(".acl2");
}
});
}
public static final ActionListener openAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file;
if (OSX) {
FileDialog fd = new FileDialog((Frame)null, "Open file");
fd.setFilenameFilter(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".lisp") || name.endsWith(".lsp")
|| name.endsWith(".acl2");
}
});
fd.setVisible(true);
String filename = fd.getFile();
file = filename == null ? null : new File(fd.getDirectory(), filename);
} else {
int response = fc.showOpenDialog(null);
file = response == JFileChooser.APPROVE_OPTION ? fc.getSelectedFile() : null;
}
if (file != null) {
IdeWindow window = new IdeWindow(file);
if (windows.size() == 1 &&
windows.get(0).isSaved &&
windows.get(0).openFile == null) {
windows.get(0).promptIfUnsavedAndClose();
}
window.setVisible(true);
}
}
};
private static final long serialVersionUID = -7435370608709935765L;
public static PrefsWindow prefsWindow = null;
static List<IdeWindow> windows = new LinkedList<IdeWindow>();
private static int untitledCount = 1;
File openFile;
boolean isSaved = true;
IdeWindow that = this;
private File workingDir;
private Acl2Parser parser;
Repl repl;
Toolbar toolbar;
JSplitPane previewSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
final int splitDividerDefaultSize = previewSplit.getDividerSize();
final CodePane editor;
JButton undoButton;
JButton redoButton;
Token tokens;
Acl2 acl2;
ProofBar proofBar;
MenuBar menuBar;
JScrollPane editorScroller;
JButton saveButton;
ActionListener saveAction;
ActionListener undoAction;
ActionListener redoAction;
ActionListener printAction;
ActionListener findAction;
ActionListener buildAction;
ActionListener includeBookAction;
ActionListener helpAction;
ActionListener reindentAction;
ActionListener admitNextAction;
ActionListener undoPrevAction;
ActionListener clearReplScrollback;
ActionListener tutorialAction;
TraceResult activeTrace;
public IdeWindow() {
this((File)null);
}
public IdeWindow(String text) {
this((File)null);
editor.setText(text);
}
public IdeWindow(File file) {
super();
windows.add(this);
openFile = file;
workingDir = openFile == null ? null : openFile.getParentFile();
previewSplit.setBorder(BorderFactory.createEmptyBorder());
previewSplit.setDividerSize(0);
previewSplit.setResizeWeight(0);
final JPanel splitMain = new JPanel();
previewSplit.setLeftComponent(splitMain);
splitMain.setLayout(new BorderLayout());
add(previewSplit);
final JPanel splitTop = new JPanel();
splitTop.setLayout(new BorderLayout());
final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
split.setTopComponent(splitTop);
- split.setOneTouchExpandable(true);
split.setResizeWeight(1);
splitMain.add(split, BorderLayout.CENTER);
editorScroller = new JScrollPane();
editorScroller.setBorder(BorderFactory.createEmptyBorder());
editorScroller.setViewportBorder(BorderFactory.createEmptyBorder());
this.getRootPane().setBorder(BorderFactory.createEmptyBorder());
splitTop.add(editorScroller, BorderLayout.CENTER);
final Preferences prefs = Preferences.userNodeForPackage(Main.class);
final String acl2Path;
if (prefs.getBoolean("customacl2", false)) {
acl2Path = prefs.get("acl2Path", "");
} else {
if (WIN) {
// HACK: oh no oh no oh no
acl2Path = "C:\\PROGRA~1\\PROOFP~1\\acl2\\run_acl2.exe";
} else {
String maybeAcl2Path = "";
try {
String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation()
.getPath();
jarPath = URLDecoder.decode(jarPath, "UTF-8");
File jarFile = new File(jarPath);
maybeAcl2Path = jarFile.getParent() + "/acl2/run_acl2";
maybeAcl2Path = maybeAcl2Path.replaceAll(" ", "\\\\ ");
} catch (NullPointerException e) {
System.err.println("Built-in ACL2 not found.");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
acl2Path = maybeAcl2Path;
}
}
parser = new Acl2Parser(workingDir, new File(acl2Path).getParentFile());
acl2 = new Acl2(acl2Path, workingDir, parser);
proofBar = new ProofBar(acl2);
editor = new CodePane(proofBar);
editorScroller.setViewportView(editor);
editorScroller.setRowHeaderView(proofBar);
helpAction = editor.getHelpAction();
repl = new Repl(this, acl2, editor);
proofBar.setLineHeight(editor.getLineHeight());
final IdeDocument doc = new IdeDocument(proofBar);
editor.setDocument(doc);
parser.addParseListener(new Acl2Parser.ParseListener() {
@Override
public void wasParsed() {
proofBar.admitUnprovenExps();
if (activeTrace != null) {
repl.traceExp(activeTrace.input);
}
}
});
editor.addParser(parser);
try {
acl2.initialize();
acl2.start();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(that, "ACL2 executable not found",
"Error", JOptionPane.ERROR_MESSAGE);
}
undoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.undoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
redoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.redoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
saveAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
};
printAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(editor);
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e1) {
e1.printStackTrace();
}
}
}
};
buildAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (!saveFile()) {
JOptionPane.showMessageDialog(that,
"Save the current file in order to build", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
final BuildWindow builder = new BuildWindow(openFile, acl2Path);
builder.setVisible(true);
builder.build();
}
};
includeBookAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
BookViewer viewer = new BookViewer(that);
viewer.setVisible(true);
}
};
admitNextAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.admitNextForm();
}
};
undoPrevAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.undoPrevForm();
}
};
clearReplScrollback = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repl.getOutput().removeAll();
}
};
reindentAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int beginLine, endLine;
try {
beginLine = editor.getLineOfOffset(editor.getSelectionStart());
endLine = editor.getLineOfOffset(editor.getSelectionEnd());
} catch (BadLocationException e) {
return;
}
for (int line = beginLine; line <= endLine; line++) {
int offset;
try {
offset = editor.getLineStartOffset(line);
} catch (BadLocationException e) {
return;
}
int eolLen = 1;
try {
String lineStr = editor.getText(offset, editor.getLineEndOffset(line)
- offset);
Matcher whitespace = Pattern.compile("^[ \t]*").matcher(lineStr);
whitespace.find();
int whitespaceLen = whitespace.group().length();
doc.remove(offset - eolLen, eolLen + whitespaceLen);
doc.insertString(offset - eolLen, "\n", null);
} catch (BadLocationException e) { }
}
}
};
setGlassPane(new JComponent() {
{
setVisible(false);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
}
});
}
private static final long serialVersionUID = 1L;
@Override
public boolean contains(int x, int y) {
return y > toolbar.getHeight();
}
@Override
public void paintComponent(Graphics g) {
// More opaque over areas we want to write on
g.setColor(new Color(.95f, .95f, .95f, .7f));
g.fillRect(proofBar.getWidth() + 2, toolbar.getHeight(), getWidth(),
editorScroller.getHeight() + 3);
g.fillRect(0, getHeight() - repl.getHeight(),
getWidth(), repl.getHeight() - repl.getInputHeight() - 10);
g.setColor(new Color(.9f, .9f, .9f, .4f));
g.fillRect(0, toolbar.getHeight(), getWidth(), getHeight());
g.setColor(new Color(0f, 0f, .7f));
g.setFont(editor.getFont().deriveFont(16f).deriveFont(Font.BOLD));
int lineHeight = (int) g.getFontMetrics().getLineMetrics("", g).getHeight();
g.drawString("1. Write your functions here.",
proofBar.getWidth() + 20,
toolbar.getHeight() + 30);
int step2Y = toolbar.getHeight() + editorScroller.getHeight() / 6 + 40;
g.drawString("2. Click to admit them.",
proofBar.getWidth() + 30,
step2Y);
g.drawLine(proofBar.getWidth() + 24,
step2Y - lineHeight / 4,
proofBar.getWidth() - 10,
step2Y - lineHeight / 4);
g.drawString("3. Test them here.",
proofBar.getWidth() + 20,
getHeight() - (int) repl.input.getPreferredScrollableViewportSize().getHeight() - 30);
}
});
tutorialAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getGlassPane().setVisible(!getGlassPane().isVisible());
}
};
final JPanel findBar = new JPanel();
final JTextField searchField = new JTextField();
findAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(splitTop.getComponentCount());
if (splitTop.getComponentCount() == 1) {
splitTop.add(findBar, BorderLayout.NORTH);
} else {
splitTop.remove(findBar);
editor.clearMarkAllHighlights();
}
splitTop.revalidate();
searchField.setText(editor.getSelectedText());
searchField.requestFocusInWindow();
}
};
findBar.setLayout(new BoxLayout(findBar, BoxLayout.X_AXIS));
findBar.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK),
BorderFactory.createEmptyBorder(0, 5, 0, 5)));
findBar.setBackground(new Color(.9f, .9f, .9f));
if (OSX) {
// TODO: make this look more like safari?
// findBar.add(Box.createGlue());
// searchField.setPreferredSize(new Dimension(300, 0));
} else {
findBar.add(new JLabel("Find: "));
}
searchField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
searchFor(searchField.getText(), true);
}
});
searchField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
findAction.actionPerformed(null);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.CHAR_UNDEFINED || c == '\n' || c == '\b'
|| e.isAltDown() || e.isMetaDown() || e.isControlDown()) {
return;
}
if (prefs.getBoolean("incsearch", true)) {
editor.markAll(searchField.getText() + c, false, false,
false);
}
}
});
searchField.putClientProperty("JTextField.variant", "search");
findBar.add(searchField);
JButton forward = new JButton(new ImageIcon("media/find_down.png"));
forward.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), true);
}
});
JButton back = new JButton(new ImageIcon("media/find_up.png"));
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), false);
}
});
back.putClientProperty("JButton.buttonType", "segmentedRoundRect");
forward.putClientProperty("JButton.buttonType", "segmentedRoundRect");
back.putClientProperty("JButton.segmentPosition", "first");
forward.putClientProperty("JButton.segmentPosition", "last");
findBar.add(back);
findBar.add(forward);
findBar.add(Box.createHorizontalStrut(4));
JButton done = new JButton("done");
done.putClientProperty("JButton.buttonType", "roundRect");
done.addActionListener(findAction);
findBar.add(done);
toolbar = new Toolbar(this);
menuBar = new MenuBar(this);
splitMain.add(toolbar, BorderLayout.NORTH);
setJMenuBar(menuBar);
// Preferences
PrefsWindow.addFontChangeListener(new FontChangeListener() {
@Override
public void fontChanged(Font font) {
editor.setFont(font);
repl.setFont(font);
proofBar.setLineHeight(editor.getLineHeight());
}
});
PrefsWindow.addWidthGuideChangeListener(new PrefsWindow.WidthGuideChangeListener() {
@Override
public void widthGuideChanged(int value) {
editor.widthGuide = value;
editor.repaint();
}
});
PrefsWindow.addToolbarVisibleListener(new PrefsWindow.ToolbarVisibleListener() {
@Override
public void toolbarVisible(boolean visible) {
toolbar.setVisible(visible);
getRootPane().revalidate();
}
});
///// Event Listeners /////
proofBar.addReadOnlyIndexChangeListener(new ProofBar.ReadOnlyIndexChangeListener() {
@Override
public void readOnlyIndexChanged(int newIndex) {
if (editor.getLastVisibleOffset() - 1 <= newIndex) {
editor.append("\n");
}
if (editor.getCaretPosition() <= newIndex + 1) {
editor.setCaretPosition(newIndex + 2);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.repaint();
}
});
}
});
editor.getCaret().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (proofBar.getReadOnlyIndex() == -1)
return;
if (editor.getCaretPosition()
- editor.getCaretOffsetFromLineStart() < proofBar.getReadOnlyIndex() + 2) {
editor.setCaretColor(transparent);
} else {
editor.setCaretColor(Color.BLACK);
}
}
});
editor.SetUndoManagerCreatedListener(new CodePane.UndoManagerCreatedListener() {
@Override
public void undoManagerCreated(UndoManager undoManager) {
proofBar.undoManager = undoManager;
}
});
doc.addDocumentListener(new DocumentListener() {
private void update(DocumentEvent e) {
List<Expression> exps = SExpUtils.topLevelExps(doc);
proofBar.adjustHeights((LinkedList<Expression>) exps);
fixUndoRedoStatus();
adjustMaximizedBounds();
setSaved(false);
}
@Override
public void changedUpdate(DocumentEvent e) {
update(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
update(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
update(e);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent arg0) {
proofBar.repaint();
}
@Override
public void windowClosing(WindowEvent arg0) {
if (that.promptIfUnsavedAndClose()) {
updateWindowMenu();
}
}
@Override
public void windowDeactivated(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowOpened(WindowEvent arg0) {
proofBar.repaint();
}
});
Toolkit.getDefaultToolkit().setDynamicLayout(false);
split.setBottomComponent(repl);
repl.setHeightChangeListener(new Repl.HeightChangeListener() {
@Override
public void heightChanged(int delta) {
// :-( http://lists.apple.com/archives/java-dev/2009/Aug/msg00087.html
// setSize(new Dimension(getWidth(), getHeight() + delta));
split.setDividerLocation(split.getDividerLocation() - delta);
}
});
if (openFile != null) {
openAndDisplay(openFile);
} else {
setTitle("untitled"
+ (untitledCount == 1 ? "" : " " + (untitledCount))
+ (!OSX ? " - Proof Pad" : ""));
untitledCount++;
}
updateWindowMenu();
setPreferredSize(new Dimension(600, 600));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setMinimumSize(new Dimension(550, 300));
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (WIN || OSX) {
setLocation((screen.width - 600) / 2 + 50 * windows.size(),
(screen.height - 800) / 2 + 50 * windows.size());
}
fixUndoRedoStatus();
split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
adjustMaximizedBounds();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent arg0) {
adjustMaximizedBounds();
}
});
addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowLostFocus(WindowEvent arg0) {
proofBar.repaint();
}
});
adjustMaximizedBounds();
pack();
editor.requestFocus();
split.setDividerLocation(.65);
}
static void updateWindowMenu() {
for (IdeWindow window : windows) {
MenuBar bar = window.menuBar;
if (bar != null) {
bar.updateWindowMenu();
}
}
}
public void setPreviewComponent(JComponent c) {
if (!isVisible()) return;
if (c instanceof TraceResult) {
activeTrace = (TraceResult) c;
} else {
activeTrace = null;
}
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
previewSplit.setRightComponent(panel);
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(c);
panel.add(scroller, BorderLayout.CENTER);
JButton closeButton = new JButton("<<");
JPanel bottom = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
bottom.add(Box.createGlue());
bottom.add(closeButton);
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int paneWidth = previewSplit.getRightComponent().getWidth();
Point loc = getLocationOnScreen();
setBounds(loc.x, loc.y, getWidth() - paneWidth - splitDividerDefaultSize, getHeight());
previewSplit.setRightComponent(null);
previewSplit.setDividerSize(0);
activeTrace = null;
}
});
panel.add(bottom, BorderLayout.SOUTH);
boolean wasPreviewOpen = previewSplit.getDividerSize() != 0;
previewSplit.setDividerSize(splitDividerDefaultSize);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
c.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Point loc = getLocationOnScreen();
int paneWidth = 75 * getFontMetrics(c.getFont()).charWidth('a');
final int winWidth = getWidth();
int newX = (int) Math.min(screenSize.getWidth() - winWidth - paneWidth, loc.x);
if (!wasPreviewOpen) {
setBounds(newX, loc.y, winWidth + paneWidth + splitDividerDefaultSize, getHeight());
// TODO: This doesn't work well on OS X, but might work on Windows or Linux.
// final int steps = 10;
// final int dx = (newX - loc.x) / steps;
// final int dw = (paneWidth + splitDividerDefaultSize) / steps;
// new Timer(30, new ActionListener() {
// int i = 0;
// @Override
// public void actionPerformed(ActionEvent e) {
// RepaintManager.currentManager(that.getRootPane()).markCompletelyClean(that.getRootPane());
// i++;
// Point winLoc = getLocationOnScreen();
// if (i == steps) {
// ((Timer) e.getSource()).stop();
// } else {
// setBounds(winLoc.x + dx, winLoc.y, getWidth() + dw, getHeight());
// }
// }
// }).start();
previewSplit.setDividerLocation(winWidth + splitDividerDefaultSize);
} else {
previewSplit.setDividerLocation(winWidth - paneWidth);
}
adjustMaximizedBounds();
}
public void fixUndoRedoStatus() {
// TODO: Show what you're undoing in the menu item or tooltip.
boolean canUndo = editor.canUndo();
boolean canRedo = editor.canRedo();
undoButton.setEnabled(canUndo);
redoButton.setEnabled(canRedo);
menuBar.undo.setEnabled(canUndo);
if (canUndo) {
menuBar.undo.setText("Undo");
} else {
menuBar.undo.setText("Can't Undo");
}
menuBar.redo.setEnabled(canRedo);
if (canRedo) {
menuBar.redo.setText("Redo");
} else {
menuBar.redo.setText("Can't Redo");
}
}
boolean promptIfUnsavedAndClose() {
return promptIfUnsavedAndQuit(null);
}
boolean promptIfUnsavedAndQuit(Iterator<IdeWindow> ii) {
int response = -1;
if (!isSaved) {
response = JOptionPane.showOptionDialog(this,
"You have unsaved changes. Do"
+ " you want to save before closing?",
"Unsaved changes", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, new String[] { "Save",
"Don't Save", "Cancel" }, "Save");
}
if (response == 0) {
saveFile();
}
if (response == 1 || isSaved) {
dispose();
acl2.terminate();
if (ii != null) {
ii.remove();
} else {
windows.remove(that);
}
if (windows.size() == 0 && !OSX) {
System.exit(0);
}
return true;
}
return false;
}
boolean saveFile() {
if (openFile == null) {
File file = null;
if (OSX) {
FileDialog fd = new FileDialog(this, "Save As...");
fd.setMode(FileDialog.SAVE);
fd.setVisible(true);
String filename = fd.getFile();
if (filename != null) {
if (filename.indexOf('.') == -1) {
filename += ".lisp";
}
file = new File(fd.getDirectory(), filename);
}
} else {
int response = fc.showSaveDialog(this);
file = response == JFileChooser.APPROVE_OPTION ? fc.getSelectedFile() : null;
}
if (file != null) {
if (file.exists()) {
int answer = JOptionPane.showConfirmDialog(this,
file.getName() + " already exists. Do you want to replace it?", "",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (answer == JOptionPane.NO_OPTION) {
return false;
}
}
openFile = file;
File oldWorkingDir = workingDir;
workingDir = openFile.getParentFile();
acl2.workingDir = workingDir;
if (oldWorkingDir == null || !oldWorkingDir.equals(workingDir)) {
try {
if (repl != null) {
repl.displayResult("Restarting ACL2 in new working directory",
MsgType.INFO);
}
acl2.restart();
} catch (IOException e) {
e.printStackTrace();
}
}
parser.workingDir = workingDir;
markOpenFileAsRecent();
} else {
return false;
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(openFile));
bw.write(editor.getText());
bw.close();
setSaved(true);
getRootPane().putClientProperty("Window.documentFile", openFile);
setTitle(openFile.getName() + (!OSX ? " - Proof Pad" : ""));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public void setSaved(boolean isSaved) {
this.isSaved = isSaved;
this.getRootPane().putClientProperty("Window.documentModified",
!isSaved);
saveButton.setEnabled(!isSaved);
menuBar.saveItem.setEnabled(!isSaved);
}
protected void openAndDisplay(File file) {
getRootPane().putClientProperty("Window.documentFile", file);
setTitle(file.getName() + (!OSX ? " - Proof Pad" : ""));
openFile = file;
Scanner scan = null;
try {
scan = new Scanner(openFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
String content = scan.useDelimiter("\\Z").next();
editor.setText(content);
editor.setCaretPosition(0);
java.util.List<Expression> exps = SExpUtils
.topLevelExps((IdeDocument) editor.getDocument());
proofBar.adjustHeights((LinkedList<Expression>) exps);
setSaved(true);
adjustMaximizedBounds();
updateWindowMenu();
markOpenFileAsRecent();
}
private void markOpenFileAsRecent() {
// Update recent files
Preferences prefs = Preferences.userNodeForPackage(Main.class);
int downTo = 10;
for (int i = 1; i <= MenuBar.RECENT_MENU_ITEMS; i++) {
String temp = prefs.get("recent" + i, "");
if (temp.equals(openFile.getAbsolutePath())) {
downTo = i;
break;
}
}
for (int i = downTo; i >= 2; i--) {
String maybeNext = prefs.get("recent" + (i - 1), null);
if (maybeNext == null)
continue;
prefs.put("recent" + i, maybeNext);
}
prefs.put("recent1", openFile.getAbsolutePath());
for (IdeWindow w : windows) {
w.menuBar.updateRecentMenu();
}
if (OSX && !Main.FAKE_WINDOWS) {
Main.menuBar.updateRecentMenu();
}
}
public void adjustMaximizedBounds() {
if (!OSX) return;
Dimension visibleSize = editorScroller.getViewport().getExtentSize();
Dimension textSize = editor.getPreferredScrollableViewportSize();
int maxWidth = Math.max(getWidth() - visibleSize.width + textSize.width
+ proofBar.getWidth(), 550);
int maxHeight = getHeight() - visibleSize.height + Math.max(textSize.height, 200);
if (previewSplit.getDividerSize() > 0) {
maxWidth += previewSplit.getRightComponent().getWidth();
}
setMaximizedBounds(new Rectangle(getLocation(), new Dimension(
maxWidth + 5, maxHeight + 5)));
}
void searchFor(String text, boolean forward) {
editor.clearMarkAllHighlights();
SearchContext sc = new SearchContext();
sc.setSearchFor(text);
sc.setSearchForward(forward);
boolean found = SearchEngine.find(editor, sc);
if (!found) {
int userCaret = editor.getCaretPosition();
editor.setCaretPosition(forward ? 0 : editor.getText().length());
found = SearchEngine.find(editor, sc);
if (!found) {
editor.setCaretPosition(userCaret);
Toolkit.getDefaultToolkit().beep();
}
}
}
public void includeBookAtCursor(String dirName, String path) {
editor.insert("(include-book \"" + path + "\""
+ (dirName == null ? "" : " :dir " + dirName) + ")" +
"\n",
editor.getCaretPosition() - editor.getCaretOffsetFromLineStart());
}
}
| true | true | public IdeWindow(File file) {
super();
windows.add(this);
openFile = file;
workingDir = openFile == null ? null : openFile.getParentFile();
previewSplit.setBorder(BorderFactory.createEmptyBorder());
previewSplit.setDividerSize(0);
previewSplit.setResizeWeight(0);
final JPanel splitMain = new JPanel();
previewSplit.setLeftComponent(splitMain);
splitMain.setLayout(new BorderLayout());
add(previewSplit);
final JPanel splitTop = new JPanel();
splitTop.setLayout(new BorderLayout());
final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
split.setTopComponent(splitTop);
split.setOneTouchExpandable(true);
split.setResizeWeight(1);
splitMain.add(split, BorderLayout.CENTER);
editorScroller = new JScrollPane();
editorScroller.setBorder(BorderFactory.createEmptyBorder());
editorScroller.setViewportBorder(BorderFactory.createEmptyBorder());
this.getRootPane().setBorder(BorderFactory.createEmptyBorder());
splitTop.add(editorScroller, BorderLayout.CENTER);
final Preferences prefs = Preferences.userNodeForPackage(Main.class);
final String acl2Path;
if (prefs.getBoolean("customacl2", false)) {
acl2Path = prefs.get("acl2Path", "");
} else {
if (WIN) {
// HACK: oh no oh no oh no
acl2Path = "C:\\PROGRA~1\\PROOFP~1\\acl2\\run_acl2.exe";
} else {
String maybeAcl2Path = "";
try {
String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation()
.getPath();
jarPath = URLDecoder.decode(jarPath, "UTF-8");
File jarFile = new File(jarPath);
maybeAcl2Path = jarFile.getParent() + "/acl2/run_acl2";
maybeAcl2Path = maybeAcl2Path.replaceAll(" ", "\\\\ ");
} catch (NullPointerException e) {
System.err.println("Built-in ACL2 not found.");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
acl2Path = maybeAcl2Path;
}
}
parser = new Acl2Parser(workingDir, new File(acl2Path).getParentFile());
acl2 = new Acl2(acl2Path, workingDir, parser);
proofBar = new ProofBar(acl2);
editor = new CodePane(proofBar);
editorScroller.setViewportView(editor);
editorScroller.setRowHeaderView(proofBar);
helpAction = editor.getHelpAction();
repl = new Repl(this, acl2, editor);
proofBar.setLineHeight(editor.getLineHeight());
final IdeDocument doc = new IdeDocument(proofBar);
editor.setDocument(doc);
parser.addParseListener(new Acl2Parser.ParseListener() {
@Override
public void wasParsed() {
proofBar.admitUnprovenExps();
if (activeTrace != null) {
repl.traceExp(activeTrace.input);
}
}
});
editor.addParser(parser);
try {
acl2.initialize();
acl2.start();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(that, "ACL2 executable not found",
"Error", JOptionPane.ERROR_MESSAGE);
}
undoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.undoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
redoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.redoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
saveAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
};
printAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(editor);
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e1) {
e1.printStackTrace();
}
}
}
};
buildAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (!saveFile()) {
JOptionPane.showMessageDialog(that,
"Save the current file in order to build", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
final BuildWindow builder = new BuildWindow(openFile, acl2Path);
builder.setVisible(true);
builder.build();
}
};
includeBookAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
BookViewer viewer = new BookViewer(that);
viewer.setVisible(true);
}
};
admitNextAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.admitNextForm();
}
};
undoPrevAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.undoPrevForm();
}
};
clearReplScrollback = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repl.getOutput().removeAll();
}
};
reindentAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int beginLine, endLine;
try {
beginLine = editor.getLineOfOffset(editor.getSelectionStart());
endLine = editor.getLineOfOffset(editor.getSelectionEnd());
} catch (BadLocationException e) {
return;
}
for (int line = beginLine; line <= endLine; line++) {
int offset;
try {
offset = editor.getLineStartOffset(line);
} catch (BadLocationException e) {
return;
}
int eolLen = 1;
try {
String lineStr = editor.getText(offset, editor.getLineEndOffset(line)
- offset);
Matcher whitespace = Pattern.compile("^[ \t]*").matcher(lineStr);
whitespace.find();
int whitespaceLen = whitespace.group().length();
doc.remove(offset - eolLen, eolLen + whitespaceLen);
doc.insertString(offset - eolLen, "\n", null);
} catch (BadLocationException e) { }
}
}
};
setGlassPane(new JComponent() {
{
setVisible(false);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
}
});
}
private static final long serialVersionUID = 1L;
@Override
public boolean contains(int x, int y) {
return y > toolbar.getHeight();
}
@Override
public void paintComponent(Graphics g) {
// More opaque over areas we want to write on
g.setColor(new Color(.95f, .95f, .95f, .7f));
g.fillRect(proofBar.getWidth() + 2, toolbar.getHeight(), getWidth(),
editorScroller.getHeight() + 3);
g.fillRect(0, getHeight() - repl.getHeight(),
getWidth(), repl.getHeight() - repl.getInputHeight() - 10);
g.setColor(new Color(.9f, .9f, .9f, .4f));
g.fillRect(0, toolbar.getHeight(), getWidth(), getHeight());
g.setColor(new Color(0f, 0f, .7f));
g.setFont(editor.getFont().deriveFont(16f).deriveFont(Font.BOLD));
int lineHeight = (int) g.getFontMetrics().getLineMetrics("", g).getHeight();
g.drawString("1. Write your functions here.",
proofBar.getWidth() + 20,
toolbar.getHeight() + 30);
int step2Y = toolbar.getHeight() + editorScroller.getHeight() / 6 + 40;
g.drawString("2. Click to admit them.",
proofBar.getWidth() + 30,
step2Y);
g.drawLine(proofBar.getWidth() + 24,
step2Y - lineHeight / 4,
proofBar.getWidth() - 10,
step2Y - lineHeight / 4);
g.drawString("3. Test them here.",
proofBar.getWidth() + 20,
getHeight() - (int) repl.input.getPreferredScrollableViewportSize().getHeight() - 30);
}
});
tutorialAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getGlassPane().setVisible(!getGlassPane().isVisible());
}
};
final JPanel findBar = new JPanel();
final JTextField searchField = new JTextField();
findAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(splitTop.getComponentCount());
if (splitTop.getComponentCount() == 1) {
splitTop.add(findBar, BorderLayout.NORTH);
} else {
splitTop.remove(findBar);
editor.clearMarkAllHighlights();
}
splitTop.revalidate();
searchField.setText(editor.getSelectedText());
searchField.requestFocusInWindow();
}
};
findBar.setLayout(new BoxLayout(findBar, BoxLayout.X_AXIS));
findBar.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK),
BorderFactory.createEmptyBorder(0, 5, 0, 5)));
findBar.setBackground(new Color(.9f, .9f, .9f));
if (OSX) {
// TODO: make this look more like safari?
// findBar.add(Box.createGlue());
// searchField.setPreferredSize(new Dimension(300, 0));
} else {
findBar.add(new JLabel("Find: "));
}
searchField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
searchFor(searchField.getText(), true);
}
});
searchField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
findAction.actionPerformed(null);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.CHAR_UNDEFINED || c == '\n' || c == '\b'
|| e.isAltDown() || e.isMetaDown() || e.isControlDown()) {
return;
}
if (prefs.getBoolean("incsearch", true)) {
editor.markAll(searchField.getText() + c, false, false,
false);
}
}
});
searchField.putClientProperty("JTextField.variant", "search");
findBar.add(searchField);
JButton forward = new JButton(new ImageIcon("media/find_down.png"));
forward.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), true);
}
});
JButton back = new JButton(new ImageIcon("media/find_up.png"));
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), false);
}
});
back.putClientProperty("JButton.buttonType", "segmentedRoundRect");
forward.putClientProperty("JButton.buttonType", "segmentedRoundRect");
back.putClientProperty("JButton.segmentPosition", "first");
forward.putClientProperty("JButton.segmentPosition", "last");
findBar.add(back);
findBar.add(forward);
findBar.add(Box.createHorizontalStrut(4));
JButton done = new JButton("done");
done.putClientProperty("JButton.buttonType", "roundRect");
done.addActionListener(findAction);
findBar.add(done);
toolbar = new Toolbar(this);
menuBar = new MenuBar(this);
splitMain.add(toolbar, BorderLayout.NORTH);
setJMenuBar(menuBar);
// Preferences
PrefsWindow.addFontChangeListener(new FontChangeListener() {
@Override
public void fontChanged(Font font) {
editor.setFont(font);
repl.setFont(font);
proofBar.setLineHeight(editor.getLineHeight());
}
});
PrefsWindow.addWidthGuideChangeListener(new PrefsWindow.WidthGuideChangeListener() {
@Override
public void widthGuideChanged(int value) {
editor.widthGuide = value;
editor.repaint();
}
});
PrefsWindow.addToolbarVisibleListener(new PrefsWindow.ToolbarVisibleListener() {
@Override
public void toolbarVisible(boolean visible) {
toolbar.setVisible(visible);
getRootPane().revalidate();
}
});
///// Event Listeners /////
proofBar.addReadOnlyIndexChangeListener(new ProofBar.ReadOnlyIndexChangeListener() {
@Override
public void readOnlyIndexChanged(int newIndex) {
if (editor.getLastVisibleOffset() - 1 <= newIndex) {
editor.append("\n");
}
if (editor.getCaretPosition() <= newIndex + 1) {
editor.setCaretPosition(newIndex + 2);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.repaint();
}
});
}
});
editor.getCaret().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (proofBar.getReadOnlyIndex() == -1)
return;
if (editor.getCaretPosition()
- editor.getCaretOffsetFromLineStart() < proofBar.getReadOnlyIndex() + 2) {
editor.setCaretColor(transparent);
} else {
editor.setCaretColor(Color.BLACK);
}
}
});
editor.SetUndoManagerCreatedListener(new CodePane.UndoManagerCreatedListener() {
@Override
public void undoManagerCreated(UndoManager undoManager) {
proofBar.undoManager = undoManager;
}
});
doc.addDocumentListener(new DocumentListener() {
private void update(DocumentEvent e) {
List<Expression> exps = SExpUtils.topLevelExps(doc);
proofBar.adjustHeights((LinkedList<Expression>) exps);
fixUndoRedoStatus();
adjustMaximizedBounds();
setSaved(false);
}
@Override
public void changedUpdate(DocumentEvent e) {
update(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
update(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
update(e);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent arg0) {
proofBar.repaint();
}
@Override
public void windowClosing(WindowEvent arg0) {
if (that.promptIfUnsavedAndClose()) {
updateWindowMenu();
}
}
@Override
public void windowDeactivated(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowOpened(WindowEvent arg0) {
proofBar.repaint();
}
});
Toolkit.getDefaultToolkit().setDynamicLayout(false);
split.setBottomComponent(repl);
repl.setHeightChangeListener(new Repl.HeightChangeListener() {
@Override
public void heightChanged(int delta) {
// :-( http://lists.apple.com/archives/java-dev/2009/Aug/msg00087.html
// setSize(new Dimension(getWidth(), getHeight() + delta));
split.setDividerLocation(split.getDividerLocation() - delta);
}
});
if (openFile != null) {
openAndDisplay(openFile);
} else {
setTitle("untitled"
+ (untitledCount == 1 ? "" : " " + (untitledCount))
+ (!OSX ? " - Proof Pad" : ""));
untitledCount++;
}
updateWindowMenu();
setPreferredSize(new Dimension(600, 600));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setMinimumSize(new Dimension(550, 300));
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (WIN || OSX) {
setLocation((screen.width - 600) / 2 + 50 * windows.size(),
(screen.height - 800) / 2 + 50 * windows.size());
}
fixUndoRedoStatus();
split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
adjustMaximizedBounds();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent arg0) {
adjustMaximizedBounds();
}
});
addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowLostFocus(WindowEvent arg0) {
proofBar.repaint();
}
});
adjustMaximizedBounds();
pack();
editor.requestFocus();
split.setDividerLocation(.65);
}
| public IdeWindow(File file) {
super();
windows.add(this);
openFile = file;
workingDir = openFile == null ? null : openFile.getParentFile();
previewSplit.setBorder(BorderFactory.createEmptyBorder());
previewSplit.setDividerSize(0);
previewSplit.setResizeWeight(0);
final JPanel splitMain = new JPanel();
previewSplit.setLeftComponent(splitMain);
splitMain.setLayout(new BorderLayout());
add(previewSplit);
final JPanel splitTop = new JPanel();
splitTop.setLayout(new BorderLayout());
final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
split.setTopComponent(splitTop);
split.setResizeWeight(1);
splitMain.add(split, BorderLayout.CENTER);
editorScroller = new JScrollPane();
editorScroller.setBorder(BorderFactory.createEmptyBorder());
editorScroller.setViewportBorder(BorderFactory.createEmptyBorder());
this.getRootPane().setBorder(BorderFactory.createEmptyBorder());
splitTop.add(editorScroller, BorderLayout.CENTER);
final Preferences prefs = Preferences.userNodeForPackage(Main.class);
final String acl2Path;
if (prefs.getBoolean("customacl2", false)) {
acl2Path = prefs.get("acl2Path", "");
} else {
if (WIN) {
// HACK: oh no oh no oh no
acl2Path = "C:\\PROGRA~1\\PROOFP~1\\acl2\\run_acl2.exe";
} else {
String maybeAcl2Path = "";
try {
String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation()
.getPath();
jarPath = URLDecoder.decode(jarPath, "UTF-8");
File jarFile = new File(jarPath);
maybeAcl2Path = jarFile.getParent() + "/acl2/run_acl2";
maybeAcl2Path = maybeAcl2Path.replaceAll(" ", "\\\\ ");
} catch (NullPointerException e) {
System.err.println("Built-in ACL2 not found.");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
acl2Path = maybeAcl2Path;
}
}
parser = new Acl2Parser(workingDir, new File(acl2Path).getParentFile());
acl2 = new Acl2(acl2Path, workingDir, parser);
proofBar = new ProofBar(acl2);
editor = new CodePane(proofBar);
editorScroller.setViewportView(editor);
editorScroller.setRowHeaderView(proofBar);
helpAction = editor.getHelpAction();
repl = new Repl(this, acl2, editor);
proofBar.setLineHeight(editor.getLineHeight());
final IdeDocument doc = new IdeDocument(proofBar);
editor.setDocument(doc);
parser.addParseListener(new Acl2Parser.ParseListener() {
@Override
public void wasParsed() {
proofBar.admitUnprovenExps();
if (activeTrace != null) {
repl.traceExp(activeTrace.input);
}
}
});
editor.addParser(parser);
try {
acl2.initialize();
acl2.start();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(that, "ACL2 executable not found",
"Error", JOptionPane.ERROR_MESSAGE);
}
undoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.undoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
redoAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editor.redoLastAction();
fixUndoRedoStatus();
editor.requestFocus();
}
};
saveAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
};
printAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(editor);
boolean doPrint = job.printDialog();
if (doPrint) {
try {
job.print();
} catch (PrinterException e1) {
e1.printStackTrace();
}
}
}
};
buildAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (!saveFile()) {
JOptionPane.showMessageDialog(that,
"Save the current file in order to build", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
final BuildWindow builder = new BuildWindow(openFile, acl2Path);
builder.setVisible(true);
builder.build();
}
};
includeBookAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
BookViewer viewer = new BookViewer(that);
viewer.setVisible(true);
}
};
admitNextAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.admitNextForm();
}
};
undoPrevAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
proofBar.undoPrevForm();
}
};
clearReplScrollback = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
repl.getOutput().removeAll();
}
};
reindentAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int beginLine, endLine;
try {
beginLine = editor.getLineOfOffset(editor.getSelectionStart());
endLine = editor.getLineOfOffset(editor.getSelectionEnd());
} catch (BadLocationException e) {
return;
}
for (int line = beginLine; line <= endLine; line++) {
int offset;
try {
offset = editor.getLineStartOffset(line);
} catch (BadLocationException e) {
return;
}
int eolLen = 1;
try {
String lineStr = editor.getText(offset, editor.getLineEndOffset(line)
- offset);
Matcher whitespace = Pattern.compile("^[ \t]*").matcher(lineStr);
whitespace.find();
int whitespaceLen = whitespace.group().length();
doc.remove(offset - eolLen, eolLen + whitespaceLen);
doc.insertString(offset - eolLen, "\n", null);
} catch (BadLocationException e) { }
}
}
};
setGlassPane(new JComponent() {
{
setVisible(false);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
}
});
}
private static final long serialVersionUID = 1L;
@Override
public boolean contains(int x, int y) {
return y > toolbar.getHeight();
}
@Override
public void paintComponent(Graphics g) {
// More opaque over areas we want to write on
g.setColor(new Color(.95f, .95f, .95f, .7f));
g.fillRect(proofBar.getWidth() + 2, toolbar.getHeight(), getWidth(),
editorScroller.getHeight() + 3);
g.fillRect(0, getHeight() - repl.getHeight(),
getWidth(), repl.getHeight() - repl.getInputHeight() - 10);
g.setColor(new Color(.9f, .9f, .9f, .4f));
g.fillRect(0, toolbar.getHeight(), getWidth(), getHeight());
g.setColor(new Color(0f, 0f, .7f));
g.setFont(editor.getFont().deriveFont(16f).deriveFont(Font.BOLD));
int lineHeight = (int) g.getFontMetrics().getLineMetrics("", g).getHeight();
g.drawString("1. Write your functions here.",
proofBar.getWidth() + 20,
toolbar.getHeight() + 30);
int step2Y = toolbar.getHeight() + editorScroller.getHeight() / 6 + 40;
g.drawString("2. Click to admit them.",
proofBar.getWidth() + 30,
step2Y);
g.drawLine(proofBar.getWidth() + 24,
step2Y - lineHeight / 4,
proofBar.getWidth() - 10,
step2Y - lineHeight / 4);
g.drawString("3. Test them here.",
proofBar.getWidth() + 20,
getHeight() - (int) repl.input.getPreferredScrollableViewportSize().getHeight() - 30);
}
});
tutorialAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getGlassPane().setVisible(!getGlassPane().isVisible());
}
};
final JPanel findBar = new JPanel();
final JTextField searchField = new JTextField();
findAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(splitTop.getComponentCount());
if (splitTop.getComponentCount() == 1) {
splitTop.add(findBar, BorderLayout.NORTH);
} else {
splitTop.remove(findBar);
editor.clearMarkAllHighlights();
}
splitTop.revalidate();
searchField.setText(editor.getSelectedText());
searchField.requestFocusInWindow();
}
};
findBar.setLayout(new BoxLayout(findBar, BoxLayout.X_AXIS));
findBar.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK),
BorderFactory.createEmptyBorder(0, 5, 0, 5)));
findBar.setBackground(new Color(.9f, .9f, .9f));
if (OSX) {
// TODO: make this look more like safari?
// findBar.add(Box.createGlue());
// searchField.setPreferredSize(new Dimension(300, 0));
} else {
findBar.add(new JLabel("Find: "));
}
searchField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
searchFor(searchField.getText(), true);
}
});
searchField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
findAction.actionPerformed(null);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.CHAR_UNDEFINED || c == '\n' || c == '\b'
|| e.isAltDown() || e.isMetaDown() || e.isControlDown()) {
return;
}
if (prefs.getBoolean("incsearch", true)) {
editor.markAll(searchField.getText() + c, false, false,
false);
}
}
});
searchField.putClientProperty("JTextField.variant", "search");
findBar.add(searchField);
JButton forward = new JButton(new ImageIcon("media/find_down.png"));
forward.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), true);
}
});
JButton back = new JButton(new ImageIcon("media/find_up.png"));
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
searchFor(searchField.getText(), false);
}
});
back.putClientProperty("JButton.buttonType", "segmentedRoundRect");
forward.putClientProperty("JButton.buttonType", "segmentedRoundRect");
back.putClientProperty("JButton.segmentPosition", "first");
forward.putClientProperty("JButton.segmentPosition", "last");
findBar.add(back);
findBar.add(forward);
findBar.add(Box.createHorizontalStrut(4));
JButton done = new JButton("done");
done.putClientProperty("JButton.buttonType", "roundRect");
done.addActionListener(findAction);
findBar.add(done);
toolbar = new Toolbar(this);
menuBar = new MenuBar(this);
splitMain.add(toolbar, BorderLayout.NORTH);
setJMenuBar(menuBar);
// Preferences
PrefsWindow.addFontChangeListener(new FontChangeListener() {
@Override
public void fontChanged(Font font) {
editor.setFont(font);
repl.setFont(font);
proofBar.setLineHeight(editor.getLineHeight());
}
});
PrefsWindow.addWidthGuideChangeListener(new PrefsWindow.WidthGuideChangeListener() {
@Override
public void widthGuideChanged(int value) {
editor.widthGuide = value;
editor.repaint();
}
});
PrefsWindow.addToolbarVisibleListener(new PrefsWindow.ToolbarVisibleListener() {
@Override
public void toolbarVisible(boolean visible) {
toolbar.setVisible(visible);
getRootPane().revalidate();
}
});
///// Event Listeners /////
proofBar.addReadOnlyIndexChangeListener(new ProofBar.ReadOnlyIndexChangeListener() {
@Override
public void readOnlyIndexChanged(int newIndex) {
if (editor.getLastVisibleOffset() - 1 <= newIndex) {
editor.append("\n");
}
if (editor.getCaretPosition() <= newIndex + 1) {
editor.setCaretPosition(newIndex + 2);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.repaint();
}
});
}
});
editor.getCaret().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (proofBar.getReadOnlyIndex() == -1)
return;
if (editor.getCaretPosition()
- editor.getCaretOffsetFromLineStart() < proofBar.getReadOnlyIndex() + 2) {
editor.setCaretColor(transparent);
} else {
editor.setCaretColor(Color.BLACK);
}
}
});
editor.SetUndoManagerCreatedListener(new CodePane.UndoManagerCreatedListener() {
@Override
public void undoManagerCreated(UndoManager undoManager) {
proofBar.undoManager = undoManager;
}
});
doc.addDocumentListener(new DocumentListener() {
private void update(DocumentEvent e) {
List<Expression> exps = SExpUtils.topLevelExps(doc);
proofBar.adjustHeights((LinkedList<Expression>) exps);
fixUndoRedoStatus();
adjustMaximizedBounds();
setSaved(false);
}
@Override
public void changedUpdate(DocumentEvent e) {
update(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
update(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
update(e);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent arg0) {
proofBar.repaint();
}
@Override
public void windowClosing(WindowEvent arg0) {
if (that.promptIfUnsavedAndClose()) {
updateWindowMenu();
}
}
@Override
public void windowDeactivated(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowOpened(WindowEvent arg0) {
proofBar.repaint();
}
});
Toolkit.getDefaultToolkit().setDynamicLayout(false);
split.setBottomComponent(repl);
repl.setHeightChangeListener(new Repl.HeightChangeListener() {
@Override
public void heightChanged(int delta) {
// :-( http://lists.apple.com/archives/java-dev/2009/Aug/msg00087.html
// setSize(new Dimension(getWidth(), getHeight() + delta));
split.setDividerLocation(split.getDividerLocation() - delta);
}
});
if (openFile != null) {
openAndDisplay(openFile);
} else {
setTitle("untitled"
+ (untitledCount == 1 ? "" : " " + (untitledCount))
+ (!OSX ? " - Proof Pad" : ""));
untitledCount++;
}
updateWindowMenu();
setPreferredSize(new Dimension(600, 600));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setMinimumSize(new Dimension(550, 300));
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (WIN || OSX) {
setLocation((screen.width - 600) / 2 + 50 * windows.size(),
(screen.height - 800) / 2 + 50 * windows.size());
}
fixUndoRedoStatus();
split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
adjustMaximizedBounds();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent arg0) {
adjustMaximizedBounds();
}
});
addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
proofBar.repaint();
}
@Override
public void windowLostFocus(WindowEvent arg0) {
proofBar.repaint();
}
});
adjustMaximizedBounds();
pack();
editor.requestFocus();
split.setDividerLocation(.65);
}
|
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java
index 9bd53dc66..c9d716965 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java
@@ -1,72 +1,72 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.provisional.p2.engine;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
public class Engine implements IEngine {
private final IProvisioningEventBus eventBus;
public Engine(IProvisioningEventBus eventBus) {
this.eventBus = eventBus;
}
public IStatus perform(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
// TODO -- Messages
if (iprofile == null)
throw new IllegalArgumentException(Messages.null_profile);
if (phaseSet == null)
throw new IllegalArgumentException(Messages.null_phaseset);
if (operands == null)
throw new IllegalArgumentException(Messages.null_operands);
if (context == null)
context = new ProvisioningContext();
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = (Profile) iprofile;
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(EngineActivator.getContext(), IProfileRegistry.class.getName());
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
EngineSession session = new EngineSession(profile, context);
MultiStatus result = phaseSet.perform(session, profile, operands, context, monitor);
- if (result.isOK()) {
+ if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
+ eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
+ session.rollback();
+ } else {
if (profile.isChanged()) {
profileRegistry.updateProfile(profile);
}
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
session.commit();
- } else if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
- eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
- session.rollback();
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
}
| false | true | public IStatus perform(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
// TODO -- Messages
if (iprofile == null)
throw new IllegalArgumentException(Messages.null_profile);
if (phaseSet == null)
throw new IllegalArgumentException(Messages.null_phaseset);
if (operands == null)
throw new IllegalArgumentException(Messages.null_operands);
if (context == null)
context = new ProvisioningContext();
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = (Profile) iprofile;
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(EngineActivator.getContext(), IProfileRegistry.class.getName());
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
EngineSession session = new EngineSession(profile, context);
MultiStatus result = phaseSet.perform(session, profile, operands, context, monitor);
if (result.isOK()) {
if (profile.isChanged()) {
profileRegistry.updateProfile(profile);
}
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
session.commit();
} else if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
session.rollback();
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
| public IStatus perform(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) {
// TODO -- Messages
if (iprofile == null)
throw new IllegalArgumentException(Messages.null_profile);
if (phaseSet == null)
throw new IllegalArgumentException(Messages.null_phaseset);
if (operands == null)
throw new IllegalArgumentException(Messages.null_operands);
if (context == null)
context = new ProvisioningContext();
if (monitor == null)
monitor = new NullProgressMonitor();
Profile profile = (Profile) iprofile;
SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(EngineActivator.getContext(), IProfileRegistry.class.getName());
profileRegistry.lockProfile(profile);
try {
eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this));
EngineSession session = new EngineSession(profile, context);
MultiStatus result = phaseSet.perform(session, profile, operands, context, monitor);
if (result.matches(IStatus.ERROR | IStatus.CANCEL)) {
eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result));
session.rollback();
} else {
if (profile.isChanged()) {
profileRegistry.updateProfile(profile);
}
eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this));
session.commit();
}
//if there is only one child status, return that status instead because it will have more context
IStatus[] children = result.getChildren();
return children.length == 1 ? children[0] : result;
} finally {
profileRegistry.unlockProfile(profile);
profile.setChanged(false);
}
}
|
diff --git a/LaTeXDraw/src/net/sf/latexdraw/generators/svg/LTextSVGGenerator.java b/LaTeXDraw/src/net/sf/latexdraw/generators/svg/LTextSVGGenerator.java
index 30128505..ac5287f9 100644
--- a/LaTeXDraw/src/net/sf/latexdraw/generators/svg/LTextSVGGenerator.java
+++ b/LaTeXDraw/src/net/sf/latexdraw/generators/svg/LTextSVGGenerator.java
@@ -1,140 +1,140 @@
package net.sf.latexdraw.generators.svg;
import net.sf.latexdraw.glib.models.interfaces.DrawingTK;
import net.sf.latexdraw.glib.models.interfaces.IText;
import net.sf.latexdraw.glib.models.interfaces.IText.TextPosition;
import net.sf.latexdraw.glib.models.interfaces.IText.TextSize;
import net.sf.latexdraw.parsers.svg.CSSColors;
import net.sf.latexdraw.parsers.svg.SVGAttributes;
import net.sf.latexdraw.parsers.svg.SVGDocument;
import net.sf.latexdraw.parsers.svg.SVGElement;
import net.sf.latexdraw.parsers.svg.SVGElements;
import net.sf.latexdraw.parsers.svg.SVGGElement;
import net.sf.latexdraw.parsers.svg.SVGTextElement;
import net.sf.latexdraw.util.LNamespace;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Defines a SVG generator for a text.<br>
*<br>
* This file is part of LaTeXDraw.<br>
* Copyright (c) 2005-2012 Arnaud BLOUIN<br>
*<br>
* LaTeXDraw is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.<br>
*<br>
* LaTeXDraw is distributed without any warranty; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.<br>
*<br>
* 11/11/07<br>
* @author Arnaud BLOUIN
* @version 3.0
*/
class LTextSVGGenerator extends LShapeSVGGenerator<IText> {
protected LTextSVGGenerator(final IText f) {
super(f);
}
/**
* Creates a text from an SVG text element.
* @param elt The source element.
* @since 2.0.0
*/
protected LTextSVGGenerator(final SVGTextElement elt) {
this(DrawingTK.getFactory().createText(true));
if(elt==null)
throw new IllegalArgumentException();
final String txt = elt.getText();
if(txt==null || txt.length()==0)
throw new IllegalArgumentException("This text is empty."); //$NON-NLS-1$
shape.setText(txt);
shape.setPosition(elt.getX(), elt.getY());
applyTransformations(elt);
}
protected LTextSVGGenerator(final SVGGElement elt) {
this(elt, true);
}
/**
* Creates a text from a latexdraw-SVG element.
* @param elt The source element.
* @since 2.0.0
*/
protected LTextSVGGenerator(final SVGGElement elt, final boolean withTransformation) {
this(DrawingTK.getFactory().createText(true));
if(elt==null)
throw new IllegalArgumentException();
final NodeList nl = elt.getElementsByTagNameNS(SVGDocument.SVG_NAMESPACE, SVGElements.SVG_TEXT);
setNumber(elt);
if(nl.getLength()>0) {
SVGTextElement text = (SVGTextElement)nl.item(0);
shape.setText(text.getText());
shape.setPosition(text.getX(), text.getY());
}
else
throw new IllegalArgumentException();
TextSize textSize;
try { textSize = TextSize.getTextSizeFromSize(Double.valueOf(elt.getAttribute(SVGAttributes.SVG_FONT_SIZE)).intValue()); }
- catch(NumberFormatException e) { textSize = null; }
+ catch(Exception e) { textSize = null; }
if(textSize!=null)
shape.setText("\\" + textSize.getLatexToken() + '{' + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_WEIGHT_BOLD.equals(elt.getAttribute(SVGAttributes.SVG_FONT_WEIGHT)))
shape.setText("\\textbf{" + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_STYLE_ITALIC.equals(elt.getAttribute(SVGAttributes.SVG_FONT_STYLE)))
shape.setText("\\emph{" + shape.getText() + '}');
shape.setLineColour(CSSColors.INSTANCE.getRGBColour(elt.getFill()));
shape.setTextPosition(TextPosition.getTextPosition(elt.getAttribute(LNamespace.LATEXDRAW_NAMESPACE + ':' + LNamespace.XML_POSITION)));
if(withTransformation)
applyTransformations(elt);
}
@Override
public SVGElement toSVG(final SVGDocument doc) {
if(doc == null)
return null;
final SVGElement root = new SVGGElement(doc);
final String ltdPref = LNamespace.LATEXDRAW_NAMESPACE + ':';
final Element txt = new SVGTextElement(doc);
root.setAttribute(ltdPref + LNamespace.XML_TYPE, LNamespace.XML_TYPE_TEXT);
root.setAttribute(SVGAttributes.SVG_ID, getSVGID());
root.setAttribute(SVGAttributes.SVG_FILL, CSSColors.INSTANCE.getColorName(shape.getLineColour(), true));
root.setAttribute(ltdPref + LNamespace.XML_POSITION, String.valueOf(shape.getTextPosition().getLatexToken()));
txt.setAttribute(SVGAttributes.SVG_X, String.valueOf(shape.getX()));
txt.setAttribute(SVGAttributes.SVG_Y, String.valueOf(shape.getY()));
txt.appendChild(doc.createCDATASection(shape.getText()));
root.appendChild(txt);
setSVGRotationAttribute(root);
return root;
}
}
| true | true | protected LTextSVGGenerator(final SVGGElement elt, final boolean withTransformation) {
this(DrawingTK.getFactory().createText(true));
if(elt==null)
throw new IllegalArgumentException();
final NodeList nl = elt.getElementsByTagNameNS(SVGDocument.SVG_NAMESPACE, SVGElements.SVG_TEXT);
setNumber(elt);
if(nl.getLength()>0) {
SVGTextElement text = (SVGTextElement)nl.item(0);
shape.setText(text.getText());
shape.setPosition(text.getX(), text.getY());
}
else
throw new IllegalArgumentException();
TextSize textSize;
try { textSize = TextSize.getTextSizeFromSize(Double.valueOf(elt.getAttribute(SVGAttributes.SVG_FONT_SIZE)).intValue()); }
catch(NumberFormatException e) { textSize = null; }
if(textSize!=null)
shape.setText("\\" + textSize.getLatexToken() + '{' + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_WEIGHT_BOLD.equals(elt.getAttribute(SVGAttributes.SVG_FONT_WEIGHT)))
shape.setText("\\textbf{" + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_STYLE_ITALIC.equals(elt.getAttribute(SVGAttributes.SVG_FONT_STYLE)))
shape.setText("\\emph{" + shape.getText() + '}');
shape.setLineColour(CSSColors.INSTANCE.getRGBColour(elt.getFill()));
shape.setTextPosition(TextPosition.getTextPosition(elt.getAttribute(LNamespace.LATEXDRAW_NAMESPACE + ':' + LNamespace.XML_POSITION)));
if(withTransformation)
applyTransformations(elt);
}
| protected LTextSVGGenerator(final SVGGElement elt, final boolean withTransformation) {
this(DrawingTK.getFactory().createText(true));
if(elt==null)
throw new IllegalArgumentException();
final NodeList nl = elt.getElementsByTagNameNS(SVGDocument.SVG_NAMESPACE, SVGElements.SVG_TEXT);
setNumber(elt);
if(nl.getLength()>0) {
SVGTextElement text = (SVGTextElement)nl.item(0);
shape.setText(text.getText());
shape.setPosition(text.getX(), text.getY());
}
else
throw new IllegalArgumentException();
TextSize textSize;
try { textSize = TextSize.getTextSizeFromSize(Double.valueOf(elt.getAttribute(SVGAttributes.SVG_FONT_SIZE)).intValue()); }
catch(Exception e) { textSize = null; }
if(textSize!=null)
shape.setText("\\" + textSize.getLatexToken() + '{' + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_WEIGHT_BOLD.equals(elt.getAttribute(SVGAttributes.SVG_FONT_WEIGHT)))
shape.setText("\\textbf{" + shape.getText() + '}');
if(SVGAttributes.SVG_FONT_STYLE_ITALIC.equals(elt.getAttribute(SVGAttributes.SVG_FONT_STYLE)))
shape.setText("\\emph{" + shape.getText() + '}');
shape.setLineColour(CSSColors.INSTANCE.getRGBColour(elt.getFill()));
shape.setTextPosition(TextPosition.getTextPosition(elt.getAttribute(LNamespace.LATEXDRAW_NAMESPACE + ':' + LNamespace.XML_POSITION)));
if(withTransformation)
applyTransformations(elt);
}
|
diff --git a/src/com/vmware/vim25/mo/ManagedObject.java b/src/com/vmware/vim25/mo/ManagedObject.java
index 6cb4fb5..84d0f7b 100644
--- a/src/com/vmware/vim25/mo/ManagedObject.java
+++ b/src/com/vmware/vim25/mo/ManagedObject.java
@@ -1,464 +1,472 @@
/*================================================================================
Copyright (c) 2008 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25.mo;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.util.Hashtable;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.util.*;
/**
* This class is intended to provide a wrapper around a managed object class.
* The abstraction will hide the web service details and make the managed
* objects OO style in the client side programming.
* Every managed object class can inherit from this and take advantage of this
* abstraction.
* @author Steve JIN ([email protected])
*/
abstract public class ManagedObject
{
private static String MO_PACKAGE_NAME = null;
static
{
MO_PACKAGE_NAME = ManagedObject.class.getPackage().getName();
}
/** holds the ServerConnection instance */
private ServerConnection serverConnection = null;
/** holds the ExtensionManager managed object reference */
private ManagedObjectReference mor = null;
protected ManagedObject()
{
}
/**
* Constructor that reuse exiting web service connection
* Use this contructor when you can re-use existing web service connection.
* @param serverConnection
* @param mor
*/
public ManagedObject(ServerConnection serverConnection, ManagedObjectReference mor)
{
this.serverConnection = serverConnection;
this.mor = mor;
}
/**
* Set the ManagedObjectReference object pointing to the managed object
*/
protected void setMOR(ManagedObjectReference mor)
{
this.mor = mor;
}
/**
* get the ManagedObjectReference object pointing to the managed object
* @return
*/
public ManagedObjectReference getMOR()
{
return this.mor;
}
/**
* Get the web service
* @return
*/
protected VimPortType getVimService()
{
return serverConnection.getVimService();
}
public ServerConnection getServerConnection()
{
return serverConnection;
}
/**
* Set up the ServerConnection, only when it hasn't been set yet.
* @param sc
*/
protected void setServerConnection(ServerConnection sc)
{
if(this.serverConnection==null)
{
this.serverConnection = sc;
}
}
protected ObjectContent retrieveObjectProperties(String[] properties)
{
ObjectSpec oSpec = PropertyCollectorUtil.creatObjectSpec(
getMOR(), Boolean.FALSE, null);
PropertySpec pSpec = PropertyCollectorUtil.createPropertySpec(
getMOR().getType(),
properties == null || properties.length == 0, //if true, all props of this obj are to be read regardless of propName
properties);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
pfSpec.setPropSet(new PropertySpec[] { pSpec });
PropertyCollector pc = getServerConnection().getServiceInstance().getPropertyCollector();
ObjectContent[] objs;
try
{
objs = pc.retrieveProperties(new PropertyFilterSpec[] { pfSpec });
} catch(Exception e)
{
throw new RuntimeException(e);
}
if (objs == null || objs[0]==null)
return null;
else
return objs[0];
}
/**
* @param propertyName The property name of current managed object
* @return it will return either an array of related data objects, or an data object itself.
* ManagedObjectReference objects are data objects!!!
* @throws RemoteException
* @throws RuntimeFault
* @throws InvalidProperty
* @
*/
protected Object getCurrentProperty(String propertyName)
{
ObjectContent objContent = retrieveObjectProperties(new String[] { propertyName });
Object propertyValue = null;
if (objContent != null)
{
DynamicProperty[] dynaProps = objContent.getPropSet();
if ((dynaProps != null) && (dynaProps[0]!= null))
{
propertyValue = PropertyCollectorUtil.convertProperty(dynaProps[0].getVal());
}
}
return propertyValue;
}
public Object getPropertyByPath(String propPath)
{
return getCurrentProperty(propPath);
}
/**
* Get multiple properties by their paths
* @param propPaths an array of strings for property path
* @return a Hashtable holding with the property path as key, and the value.
* @throws InvalidProperty
* @throws RuntimeFault
* @throws RemoteException
*/
public Hashtable getPropertiesByPaths(String[] propPaths)
throws InvalidProperty, RuntimeFault, RemoteException
{
Hashtable[] pht = PropertyCollectorUtil.retrieveProperties(
new ManagedObject[] { this }, getMOR().getType(), propPaths);
if(pht.length!=0)
return pht[0];
else
return null;
}
protected ManagedObject[] getManagedObjects(String propName, boolean mixedType)
{
Object object = getCurrentProperty(propName);
ManagedObjectReference[] mors = null;
if(object instanceof ManagedObjectReference[])
{
mors = (ManagedObjectReference[]) object;
}
if(mors==null || mors.length==0)
{
return new ManagedObject[] {};
}
Object mos = new ManagedObject[mors.length];;
try
{
Class moClass = null;
if(mixedType==false)
{
moClass = Class.forName(MO_PACKAGE_NAME + "." + mors[0].getType());
mos = Array.newInstance(moClass, mors.length);
}
for(int i=0; i<mors.length; i++)
{
if(mixedType == true )
{
moClass = Class.forName(MO_PACKAGE_NAME + "." + mors[i].getType());
}
Constructor constructor = moClass.getConstructor(
new Class[] {ServerConnection.class, ManagedObjectReference.class});
Array.set(mos, i,
constructor.newInstance(new Object[] { getServerConnection(), mors[i]}) );
}
} catch(Exception e)
{
e.printStackTrace();
}
return (ManagedObject[]) mos;
}
protected ManagedObject[] getManagedObjects(String propName)
{
return getManagedObjects(propName, false);
}
protected Datastore[] getDatastores(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new Datastore[] {};
}
return (Datastore[]) objs;
}
protected Network[] getNetworks(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new Network[] {};
}
return (Network[]) objs;
}
protected VirtualMachine[] getVms(String propName)
{
ManagedObject[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new VirtualMachine[] {};
}
return (VirtualMachine[]) objs;
}
protected PropertyFilter[] getFilter(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new PropertyFilter[] {};
}
return (PropertyFilter[]) objs;
}
protected ResourcePool[] getResourcePools(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new ResourcePool[] {};
}
return (ResourcePool[]) objs;
}
protected Task[] getTasks(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new Task[] {};
}
return (Task[]) objs;
}
protected ScheduledTask[] getScheduledTasks(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new ScheduledTask[] {};
}
return (ScheduledTask[]) objs;
}
protected View[] getViews(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new View[] {};
}
return (View[]) objs;
}
protected HostSystem[] getHosts(String propName)
{
Object[] objs = getManagedObjects(propName);
if(objs.length == 0)
{
return new HostSystem[] {};
}
return (HostSystem[]) objs;
}
protected ManagedObject getManagedObject(String propName)
{
ManagedObjectReference mor = (ManagedObjectReference) getCurrentProperty(propName);
return MorUtil.createExactManagedObject(getServerConnection(), mor);
}
/**
* Handle Updates for a single object.
* waits till expected values of properties to check are reached
* Destroys the ObjectFilter when done.
* @param filterProps Properties list to filter
* @param endWaitProps
* Properties list to check for expected values
* these be properties of a property in the filter properties list
* @param expectedVals values for properties to end the wait
* @return true indicating expected values were met, and false otherwise
* @throws RemoteException
* @throws RuntimeFault
* @throws InvalidProperty
*/
protected Object[] waitForValues(String[] filterProps, String[] endWaitProps, Object[][] expectedVals) throws InvalidProperty, RuntimeFault, RemoteException
{
String version = "";
Object[] endVals = new Object[endWaitProps.length];
Object[] filterVals = new Object[filterProps.length];
ObjectSpec oSpec = PropertyCollectorUtil.creatObjectSpec(
getMOR(), Boolean.FALSE, null);
PropertySpec pSpec = PropertyCollectorUtil.createPropertySpec(
getMOR().getType(),
filterProps == null || filterProps.length == 0, //if true, all props of this obj are to be read regardless of propName
filterProps);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.setObjectSet(new ObjectSpec[] { oSpec });
spec.setPropSet(new PropertySpec[] { pSpec });
PropertyCollector pc = serverConnection.getServiceInstance().getPropertyCollector();
PropertyFilter pf = pc.createFilter(spec, true);
boolean reached = false;
while (!reached)
{
UpdateSet updateset = pc.waitForUpdates(version);
if(updateset==null)
{
continue;
}
version = updateset.getVersion();
PropertyFilterUpdate[] filtupary = updateset.getFilterSet();
if (filtupary == null)
{
continue;
}
// Make this code more general purpose when PropCol changes later.
for (int i = 0; i < filtupary.length; i++)
{
PropertyFilterUpdate filtup = filtupary[i];
+ if(filtup==null)
+ {
+ continue;
+ }
ObjectUpdate[] objupary = filtup.getObjectSet();
- for (int j = 0; j < objupary.length; j++)
+ for (int j = 0; objupary!=null && j < objupary.length; j++)
{
ObjectUpdate objup = objupary[j];
+ if(objup==null)
+ {
+ continue;
+ }
PropertyChange[] propchgary = objup.getChangeSet();
for (int k = 0; propchgary!=null && k < propchgary.length; k++)
{
PropertyChange propchg = propchgary[k];
updateValues(endWaitProps, endVals, propchg);
updateValues(filterProps, filterVals, propchg);
}
}
}
// Check if the expected values have been reached and exit the loop if done.
// Also exit the WaitForUpdates loop if this is the case.
for (int chgi = 0; chgi < endVals.length && !reached; chgi++)
{
for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++)
{
Object expctdval = expectedVals[chgi][vali];
reached = expctdval.equals(endVals[chgi]) || reached;
}
}
}
pf.destroyPropertyFilter();
return filterVals;
}
private void updateValues(String[] props, Object[] vals, PropertyChange propchg)
{
for (int i = 0; i < props.length; i++)
{
if (propchg.getName().lastIndexOf(props[i]) >= 0)
{
if (propchg.getOp() == PropertyChangeOp.remove)
{
vals[i] = "";
}
else
{
vals[i] = propchg.getVal();
}
}
}
}
public String toString()
{
return mor.getType() + ":" + mor.get_value()
+ " @ " + getServerConnection().getUrl();
}
}
| false | true | protected Object[] waitForValues(String[] filterProps, String[] endWaitProps, Object[][] expectedVals) throws InvalidProperty, RuntimeFault, RemoteException
{
String version = "";
Object[] endVals = new Object[endWaitProps.length];
Object[] filterVals = new Object[filterProps.length];
ObjectSpec oSpec = PropertyCollectorUtil.creatObjectSpec(
getMOR(), Boolean.FALSE, null);
PropertySpec pSpec = PropertyCollectorUtil.createPropertySpec(
getMOR().getType(),
filterProps == null || filterProps.length == 0, //if true, all props of this obj are to be read regardless of propName
filterProps);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.setObjectSet(new ObjectSpec[] { oSpec });
spec.setPropSet(new PropertySpec[] { pSpec });
PropertyCollector pc = serverConnection.getServiceInstance().getPropertyCollector();
PropertyFilter pf = pc.createFilter(spec, true);
boolean reached = false;
while (!reached)
{
UpdateSet updateset = pc.waitForUpdates(version);
if(updateset==null)
{
continue;
}
version = updateset.getVersion();
PropertyFilterUpdate[] filtupary = updateset.getFilterSet();
if (filtupary == null)
{
continue;
}
// Make this code more general purpose when PropCol changes later.
for (int i = 0; i < filtupary.length; i++)
{
PropertyFilterUpdate filtup = filtupary[i];
ObjectUpdate[] objupary = filtup.getObjectSet();
for (int j = 0; j < objupary.length; j++)
{
ObjectUpdate objup = objupary[j];
PropertyChange[] propchgary = objup.getChangeSet();
for (int k = 0; propchgary!=null && k < propchgary.length; k++)
{
PropertyChange propchg = propchgary[k];
updateValues(endWaitProps, endVals, propchg);
updateValues(filterProps, filterVals, propchg);
}
}
}
// Check if the expected values have been reached and exit the loop if done.
// Also exit the WaitForUpdates loop if this is the case.
for (int chgi = 0; chgi < endVals.length && !reached; chgi++)
{
for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++)
{
Object expctdval = expectedVals[chgi][vali];
reached = expctdval.equals(endVals[chgi]) || reached;
}
}
}
pf.destroyPropertyFilter();
return filterVals;
}
| protected Object[] waitForValues(String[] filterProps, String[] endWaitProps, Object[][] expectedVals) throws InvalidProperty, RuntimeFault, RemoteException
{
String version = "";
Object[] endVals = new Object[endWaitProps.length];
Object[] filterVals = new Object[filterProps.length];
ObjectSpec oSpec = PropertyCollectorUtil.creatObjectSpec(
getMOR(), Boolean.FALSE, null);
PropertySpec pSpec = PropertyCollectorUtil.createPropertySpec(
getMOR().getType(),
filterProps == null || filterProps.length == 0, //if true, all props of this obj are to be read regardless of propName
filterProps);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.setObjectSet(new ObjectSpec[] { oSpec });
spec.setPropSet(new PropertySpec[] { pSpec });
PropertyCollector pc = serverConnection.getServiceInstance().getPropertyCollector();
PropertyFilter pf = pc.createFilter(spec, true);
boolean reached = false;
while (!reached)
{
UpdateSet updateset = pc.waitForUpdates(version);
if(updateset==null)
{
continue;
}
version = updateset.getVersion();
PropertyFilterUpdate[] filtupary = updateset.getFilterSet();
if (filtupary == null)
{
continue;
}
// Make this code more general purpose when PropCol changes later.
for (int i = 0; i < filtupary.length; i++)
{
PropertyFilterUpdate filtup = filtupary[i];
if(filtup==null)
{
continue;
}
ObjectUpdate[] objupary = filtup.getObjectSet();
for (int j = 0; objupary!=null && j < objupary.length; j++)
{
ObjectUpdate objup = objupary[j];
if(objup==null)
{
continue;
}
PropertyChange[] propchgary = objup.getChangeSet();
for (int k = 0; propchgary!=null && k < propchgary.length; k++)
{
PropertyChange propchg = propchgary[k];
updateValues(endWaitProps, endVals, propchg);
updateValues(filterProps, filterVals, propchg);
}
}
}
// Check if the expected values have been reached and exit the loop if done.
// Also exit the WaitForUpdates loop if this is the case.
for (int chgi = 0; chgi < endVals.length && !reached; chgi++)
{
for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++)
{
Object expctdval = expectedVals[chgi][vali];
reached = expctdval.equals(endVals[chgi]) || reached;
}
}
}
pf.destroyPropertyFilter();
return filterVals;
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/refund/RefundInvoice.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/refund/RefundInvoice.java
index b37e1b80..473305ec 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/refund/RefundInvoice.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/refund/RefundInvoice.java
@@ -1,79 +1,79 @@
package pt.ist.expenditureTrackingSystem.domain.acquisitions.refund;
import java.math.BigDecimal;
import org.joda.time.LocalDate;
import pt.ist.expenditureTrackingSystem.domain.DomainException;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RequestItem;
import pt.ist.expenditureTrackingSystem.domain.organization.Supplier;
import myorg.domain.util.Money;
import pt.ist.fenixframework.pstm.Transaction;
public class RefundInvoice extends RefundInvoice_Base {
public RefundInvoice(String invoiceNumber, LocalDate invoiceDate, Money value, BigDecimal vatValue, Money refundableValue,
RefundItem item, Supplier supplier) {
super();
check(item, supplier, value, vatValue, refundableValue);
this.setExpenditureTrackingSystem(ExpenditureTrackingSystem.getInstance());
this.setInvoiceNumber(invoiceNumber);
this.setInvoiceDate(invoiceDate);
this.setValue(value);
this.setVatValue(vatValue);
this.setRefundableValue(refundableValue);
this.setRefundItem(item);
this.setSupplier(supplier);
}
private void check(RequestItem item, Supplier supplier, Money value, BigDecimal vatValue, Money refundableValue) {
if (!supplier.isFundAllocationAllowed(value)) {
throw new DomainException("acquisitionRequestItem.message.exception.fundAllocationNotAllowed");
}
Money realValue = item.getRealValue();
Money estimatedValue = item.getValue();
if ((realValue != null && realValue.add(refundableValue).isGreaterThan(estimatedValue)) || realValue == null
&& refundableValue.isGreaterThan(estimatedValue)) {
throw new DomainException("refundItem.message.info.realValueLessThanRefundableValue");
}
- if (value.addPercentage(vatValue).isLessThan(refundableValue)) {
+ if (new Money(value.addPercentage(vatValue).getRoundedValue()).isLessThan(refundableValue)) {
throw new DomainException("refundItem.message.info.refundableValueCannotBeBiggerThanInvoiceValue");
}
}
public RefundInvoice(String invoiceNumber, LocalDate invoiceDate, Money value, BigDecimal vatValue, Money refundableValue,
byte[] invoiceFile, String filename, RefundItem item, Supplier supplier) {
this(invoiceNumber, invoiceDate, value, vatValue, refundableValue, item, supplier);
RefundableInvoiceFile refundInvoice = new RefundableInvoiceFile(this, invoiceFile, filename);
//item.getRequest().addInvoice(refundInvoice);
item.addInvoicesFiles(refundInvoice);
}
public void delete() {
getRefundItem().clearRealShareValues();
removeRefundItem();
removeSupplier();
removeExpenditureTrackingSystem();
getFile().delete();
Transaction.deleteObject(this);
}
public void editValues(Money value, BigDecimal vatValue, Money refundableValue) {
check(getRefundItem(), getSupplier(), value, vatValue, refundableValue);
this.setValue(value);
this.setVatValue(vatValue);
this.setRefundableValue(refundableValue);
}
public void resetValues() {
this.setValue(Money.ZERO);
this.setVatValue(BigDecimal.ZERO);
this.setRefundableValue(Money.ZERO);
}
public Money getValueWithVat() {
return getValue().addPercentage(getVatValue());
}
}
| true | true | private void check(RequestItem item, Supplier supplier, Money value, BigDecimal vatValue, Money refundableValue) {
if (!supplier.isFundAllocationAllowed(value)) {
throw new DomainException("acquisitionRequestItem.message.exception.fundAllocationNotAllowed");
}
Money realValue = item.getRealValue();
Money estimatedValue = item.getValue();
if ((realValue != null && realValue.add(refundableValue).isGreaterThan(estimatedValue)) || realValue == null
&& refundableValue.isGreaterThan(estimatedValue)) {
throw new DomainException("refundItem.message.info.realValueLessThanRefundableValue");
}
if (value.addPercentage(vatValue).isLessThan(refundableValue)) {
throw new DomainException("refundItem.message.info.refundableValueCannotBeBiggerThanInvoiceValue");
}
}
| private void check(RequestItem item, Supplier supplier, Money value, BigDecimal vatValue, Money refundableValue) {
if (!supplier.isFundAllocationAllowed(value)) {
throw new DomainException("acquisitionRequestItem.message.exception.fundAllocationNotAllowed");
}
Money realValue = item.getRealValue();
Money estimatedValue = item.getValue();
if ((realValue != null && realValue.add(refundableValue).isGreaterThan(estimatedValue)) || realValue == null
&& refundableValue.isGreaterThan(estimatedValue)) {
throw new DomainException("refundItem.message.info.realValueLessThanRefundableValue");
}
if (new Money(value.addPercentage(vatValue).getRoundedValue()).isLessThan(refundableValue)) {
throw new DomainException("refundItem.message.info.refundableValueCannotBeBiggerThanInvoiceValue");
}
}
|
diff --git a/src/org/opensolaris/opengrok/history/JDBCHistoryCache.java b/src/org/opensolaris/opengrok/history/JDBCHistoryCache.java
index 8553736..aee7c51 100644
--- a/src/org/opensolaris/opengrok/history/JDBCHistoryCache.java
+++ b/src/org/opensolaris/opengrok/history/JDBCHistoryCache.java
@@ -1,809 +1,809 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.history;
import java.io.File;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opensolaris.opengrok.OpenGrokLogger;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.jdbc.ConnectionManager;
import org.opensolaris.opengrok.jdbc.ConnectionResource;
import org.opensolaris.opengrok.jdbc.InsertQuery;
import org.opensolaris.opengrok.jdbc.PreparedQuery;
class JDBCHistoryCache implements HistoryCache {
private static final String DERBY_EMBEDDED_DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
private static final String SCHEMA = "APP";
/** The names of all the tables created by this class. */
private static final String[] TABLES = {
"REPOSITORIES", "FILES", "AUTHORS", "CHANGESETS", "FILECHANGES"
};
/**
* The number of times to retry an operation that failed in a way that
* indicates that it may succeed if it's tried again.
*/
private static final int MAX_RETRIES = 2;
private ConnectionManager connectionManager;
private final String jdbcDriverClass;
private final String jdbcConnectionURL;
/**
* Create a new cache instance with the default JDBC driver and URL.
*/
JDBCHistoryCache() {
this(DERBY_EMBEDDED_DRIVER,
"jdbc:derby:" +
RuntimeEnvironment.getInstance().getDataRootPath() +
File.separator + "cachedb;create=true");
}
/**
* Create a new cache instance with the specified JDBC driver and URL.
*
* @param jdbcDriverClass JDBC driver class to access the database backend
* @param url the JDBC url to the database
*/
JDBCHistoryCache(String jdbcDriverClass, String url) {
this.jdbcDriverClass = jdbcDriverClass;
this.jdbcConnectionURL = url;
}
/**
* Handle an {@code SQLException}. If the exception indicates that the
* operation may succeed if it's retried and the number of attempts hasn't
* exceeded the limit defined by {@link #MAX_RETRIES}, ignore it and let
* the caller retry the operation. Otherwise, re-throw the exception.
*
* @param sqle the exception to handle
* @param attemptNo the attempt number, first attempt is 0
* @throws SQLException if the operation shouldn't be retried
*/
private static void handleSQLException(SQLException sqle, int attemptNo)
throws SQLException {
// TODO: When we only support JDK 6 or later, check for
// SQLTransactionRollbackException instead of SQLState. Or
// perhaps SQLTransientException.
boolean isTransient = false;
Throwable t = sqle;
do {
if (t instanceof SQLException) {
String sqlState = ((SQLException) t).getSQLState();
isTransient = (sqlState != null) && sqlState.startsWith("40");
}
t = t.getCause();
} while (!isTransient && t != null);
if (isTransient && attemptNo < MAX_RETRIES) {
Logger logger = OpenGrokLogger.getLogger();
logger.info("Transient database failure detected. Retrying.");
logger.log(Level.FINE, "Transient database failure details:", sqle);
} else {
throw sqle;
}
}
// Many of the tables contain columns with identical names and types,
// so there will be duplicate strings. Suppress warning from PMD.
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
private static void initDB(Statement s) throws SQLException {
// TODO Store a database version which is incremented on each
// format change. When a version change is detected, drop the database
// (or possibly in the future: add some upgrade code that makes the
// necessary changes between versions). For now, just check if the
// tables exist, and create them if necessary.
DatabaseMetaData dmd = s.getConnection().getMetaData();
if (!tableExists(dmd, SCHEMA, "REPOSITORIES")) {
s.executeUpdate("CREATE TABLE REPOSITORIES (" +
"ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " +
"PATH VARCHAR(32672) UNIQUE NOT NULL)");
}
if (!tableExists(dmd, SCHEMA, "FILES")) {
s.executeUpdate("CREATE TABLE FILES (" +
"ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " +
"PATH VARCHAR(32672) NOT NULL, " +
"REPOSITORY INT NOT NULL REFERENCES REPOSITORIES " +
"ON DELETE CASCADE, " +
"UNIQUE (REPOSITORY, PATH))");
}
if (!tableExists(dmd, SCHEMA, "AUTHORS")) {
s.executeUpdate("CREATE TABLE AUTHORS (" +
"ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " +
"REPOSITORY INT NOT NULL REFERENCES REPOSITORIES " +
"ON DELETE CASCADE, " +
"NAME VARCHAR(32672) NOT NULL, " +
"UNIQUE (REPOSITORY, NAME))");
}
if (!tableExists(dmd, SCHEMA, "CHANGESETS")) {
s.executeUpdate("CREATE TABLE CHANGESETS (" +
"ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " +
"REPOSITORY INT NOT NULL REFERENCES REPOSITORIES " +
"ON DELETE CASCADE, " +
"REVISION VARCHAR(1024) NOT NULL, " +
"AUTHOR INT NOT NULL REFERENCES AUTHORS " +
"ON DELETE CASCADE, " +
"TIME TIMESTAMP NOT NULL, " +
"MESSAGE VARCHAR(32672) NOT NULL, " +
"UNIQUE (REPOSITORY, REVISION))");
// Create a descending index on the identity column to allow
// faster retrieval of history in reverse chronological order in
// get() and maximum value in getLatestCachedRevision().
s.executeUpdate("CREATE UNIQUE INDEX IDX_CHANGESETS_ID_DESC " +
"ON CHANGESETS(ID DESC)");
}
if (!tableExists(dmd, SCHEMA, "FILECHANGES")) {
s.executeUpdate("CREATE TABLE FILECHANGES (" +
"ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " +
"FILE INT NOT NULL REFERENCES FILES " +
"ON DELETE CASCADE, " +
"CHANGESET INT NOT NULL REFERENCES CHANGESETS " +
"ON DELETE CASCADE, " +
"UNIQUE (FILE, CHANGESET))");
}
}
private static boolean tableExists(
DatabaseMetaData dmd, String schema, String table)
throws SQLException {
ResultSet rs = dmd.getTables(
null, schema, table, new String[] {"TABLE"});
try {
return rs.next();
} finally {
rs.close();
}
}
public void initialize() throws HistoryException {
try {
connectionManager =
new ConnectionManager(jdbcDriverClass, jdbcConnectionURL);
for (int i = 0;; i++) {
final ConnectionResource conn =
connectionManager.getConnectionResource();
try {
final Statement stmt = conn.createStatement();
try {
initDB(stmt);
} finally {
stmt.close();
}
conn.commit();
// Success! Break out of the loop.
return;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
} finally {
connectionManager.releaseConnection(conn);
}
}
} catch (Exception e) {
throw new HistoryException(e);
}
}
private static final PreparedQuery IS_DIR_IN_CACHE = new PreparedQuery(
"SELECT 1 FROM REPOSITORIES R WHERE R.PATH = ? AND EXISTS " +
"(SELECT 1 FROM FILES F WHERE F.REPOSITORY = R.ID AND " +
"F.PATH LIKE ? ESCAPE '#')");
// We do check the return value from ResultSet.next(), but PMD doesn't
// understand it, so suppress the warning.
@SuppressWarnings("PMD.CheckResultSet")
public boolean hasCacheForDirectory(File file, Repository repository)
throws HistoryException {
assert file.isDirectory();
try {
for (int i = 0;; i++) {
final ConnectionResource conn =
connectionManager.getConnectionResource();
try {
PreparedStatement ps = conn.getStatement(IS_DIR_IN_CACHE);
ps.setString(1, toUnixPath(repository.getDirectoryName()));
ps.setString(2, createDirPattern(
getRelativePath(file, repository), '#'));
ResultSet rs = ps.executeQuery();
try {
return rs.next();
} finally {
rs.close();
}
} catch (SQLException sqle) {
handleSQLException(sqle, i);
} finally {
connectionManager.releaseConnection(conn);
}
}
} catch (SQLException sqle) {
throw new HistoryException(sqle);
}
}
/**
* Get path name with all file separators replaced with '/'.
*/
private static String toUnixPath(String path) {
return path.replace(File.separatorChar, '/');
}
/**
* Get path name with all file separators replaced with '/'.
*/
private static String toUnixPath(File file) throws HistoryException {
try {
return toUnixPath(file.getCanonicalPath());
} catch (IOException ioe) {
throw new HistoryException(ioe);
}
}
/**
* Get the path of a file relative to the repository root.
* @param file the file to get the path for
* @param repository the repository
* @return relative path for {@code file} with unix file separators
*/
private static String getRelativePath(File file, Repository repository)
throws HistoryException {
String filePath = toUnixPath(file);
String reposPath = toUnixPath(repository.getDirectoryName());
return getRelativePath(filePath, reposPath);
}
/**
* Get the path of a file relative to the source root.
* @param file the file to get the path for
* @return relative path for {@code file} with unix file separators
*/
private static String getSourceRootRelativePath(File file)
throws HistoryException {
String filePath = toUnixPath(file);
String rootPath = RuntimeEnvironment.getInstance().getSourceRootPath();
return getRelativePath(filePath, rootPath);
}
/**
* Get the path of a file relative to the specified root directory.
* @param filePath the canonical path of the file to get the relative
* path for
* @param rootPath the canonical path of the root directory
* @return relative path with unix file separators
*/
private static String getRelativePath(String filePath, String rootPath) {
assert filePath.startsWith(rootPath);
return filePath.substring(rootPath.length());
}
/**
* Build a statement that can be used to fetch the history for a given
* file or directory.
*
* @param isDir whether the statement should return history for a
* directory (if {@code true}) or for a file (if {@code false})
* @return an SQL statement that fetches the history for a file/directory
*/
private static String buildGetHistoryQuery(boolean isDir) {
return "SELECT CS.REVISION, A.NAME, CS.TIME, CS.MESSAGE, F2.PATH " +
"FROM CHANGESETS CS, FILECHANGES FC, REPOSITORIES R, " +
"FILES F, AUTHORS A, FILECHANGES FC2, FILES F2 " +
"WHERE R.PATH = ? AND " +
(isDir ? "F.PATH LIKE ? ESCAPE '#'" : "F.PATH = ?") +
" AND F.REPOSITORY = R.ID AND A.REPOSITORY = R.ID AND " +
"CS.ID = FC.CHANGESET AND R.ID = CS.REPOSITORY AND " +
"FC.FILE = F.ID AND A.ID = CS.AUTHOR AND " +
"CS.ID = FC2.CHANGESET AND FC2.FILE = F2.ID " +
"ORDER BY CS.ID DESC";
}
/**
* Statement that gets the history for the specified file and repository.
* The result is ordered in reverse chronological order to match the
* required ordering for {@link HistoryCache#get(File, Repository)}.
*/
private static final PreparedQuery GET_FILE_HISTORY =
new PreparedQuery(buildGetHistoryQuery(false));
/**
* Statement that gets the history for all files matching a pattern in the
* given repository. The result is ordered in reverse chronological order
* to match the required ordering for
* {@link HistoryCache#get(File, Repository)}.
*/
private static final PreparedQuery GET_DIR_HISTORY =
new PreparedQuery(buildGetHistoryQuery(true));
public History get(File file, Repository repository)
throws HistoryException {
try {
for (int i = 0;; i++) {
try {
return getHistory(file, repository);
} catch (SQLException sqle) {
handleSQLException(sqle, i);
}
}
} catch (SQLException sqle) {
throw new HistoryException(sqle);
}
}
/**
* Helper for {@link #get(File, Repository)}.
*/
private History getHistory(File file, Repository repository)
throws HistoryException, SQLException {
final String filePath = getSourceRootRelativePath(file);
final String reposPath = toUnixPath(repository.getDirectoryName());
final ArrayList<HistoryEntry> entries = new ArrayList<HistoryEntry>();
final ConnectionResource conn =
connectionManager.getConnectionResource();
try {
final PreparedStatement ps;
if (file.isDirectory()) {
// Fetch history for all files under this directory. Match
// file names against a pattern with a LIKE clause.
ps = conn.getStatement(GET_DIR_HISTORY);
ps.setString(2, createDirPattern(filePath, '#'));
} else {
// Fetch history for a single file only.
ps = conn.getStatement(GET_FILE_HISTORY);
ps.setString(2, filePath);
}
ps.setString(1, reposPath);
ResultSet rs = ps.executeQuery();
try {
String currentRev = null;
HistoryEntry entry = null;
while (rs.next()) {
String revision = rs.getString(1);
if (!revision.equals(currentRev)) {
currentRev = revision;
String author = rs.getString(2);
Timestamp time = rs.getTimestamp(3);
String message = rs.getString(4);
entry = new HistoryEntry(
revision, time, author, message, true);
entries.add(entry);
}
String fileName = rs.getString(5);
entry.addFile(fileName);
}
} finally {
rs.close();
}
} finally {
connectionManager.releaseConnection(conn);
}
History history = new History();
history.setHistoryEntries(entries);
return history;
}
/**
* Create a pattern that can be used to match file names against a
* directory name with LIKE.
*
* @param path the path name of the directory
* @param escape the escape character used in the LIKE query
* @return a pattern for use in LIKE queries
*/
private static String createDirPattern(String path, char escape) {
StringBuilder escaped = new StringBuilder(path.length() + 2);
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c == '%' || c == '_' || c == escape) {
escaped.append(escape);
}
escaped.append(c);
}
escaped.append("/%");
return escaped.toString();
}
private static PreparedQuery GET_REPOSITORY = new PreparedQuery(
"SELECT ID FROM REPOSITORIES WHERE PATH = ?");
private static InsertQuery INSERT_REPOSITORY = new InsertQuery(
"INSERT INTO REPOSITORIES(PATH) VALUES ?");
public void store(History history, Repository repository)
throws HistoryException {
try {
final ConnectionResource conn =
connectionManager.getConnectionResource();
try {
storeHistory(conn, history, repository);
// The tables may have grown significantly and made the
// index cardinality statistics outdated. Call this method
// as a workaround to keep the statistics up to date.
// Without this, we have observed very bad performance when
// calling get(), because the outdated statistics can make
// the optimizer choose a sub-optimal join strategy.
updateIndexCardinalityStatistics(conn);
} finally {
connectionManager.releaseConnection(conn);
}
} catch (SQLException sqle) {
throw new HistoryException(sqle);
}
}
private static InsertQuery ADD_CHANGESET = new InsertQuery(
"INSERT INTO CHANGESETS" +
"(REPOSITORY, REVISION, AUTHOR, TIME, MESSAGE) " +
"VALUES (?,?,?,?,?)");
private static PreparedQuery ADD_FILECHANGE = new PreparedQuery(
"INSERT INTO FILECHANGES(CHANGESET, FILE) VALUES (?,?)");
private void storeHistory(ConnectionResource conn, History history,
Repository repository) throws SQLException {
Integer reposId = null;
Map<String, Integer> authors = null;
Map<String, Integer> files = null;
PreparedStatement addChangeset = null;
PreparedStatement addFilechange = null;
for (int i = 0;; i++) {
try {
if (reposId == null) {
reposId = getRepositoryId(conn, repository);
conn.commit();
}
if (authors == null) {
authors = getAuthors(conn, history, reposId);
conn.commit();
}
if (files == null) {
files = getFiles(conn, history, reposId);
conn.commit();
}
if (addChangeset == null) {
addChangeset = conn.getStatement(ADD_CHANGESET);
}
if (addFilechange == null) {
addFilechange = conn.getStatement(ADD_FILECHANGE);
}
// Success! Break out of the loop.
break;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
addChangeset.setInt(1, reposId);
// getHistoryEntries() returns the entries in reverse chronological
// order, but we want to insert them in chronological order so that
// their auto-generated identity column can be used as a chronological
// ordering column. Otherwise, incremental updates will make the
// identity column unusable for chronological ordering. So therefore
// we walk the list backwards.
List<HistoryEntry> entries = history.getHistoryEntries();
for (ListIterator<HistoryEntry> it =
entries.listIterator(entries.size());
it.hasPrevious();) {
+ HistoryEntry entry = it.previous();
retry:
for (int i = 0;; i++) {
try {
- HistoryEntry entry = it.previous();
addChangeset.setString(2, entry.getRevision());
addChangeset.setInt(3, authors.get(entry.getAuthor()));
addChangeset.setTimestamp(4,
new Timestamp(entry.getDate().getTime()));
addChangeset.setString(5, entry.getMessage());
addChangeset.executeUpdate();
int changesetId = getGeneratedIntKey(addChangeset);
addFilechange.setInt(1, changesetId);
for (String file : entry.getFiles()) {
int fileId = files.get(toUnixPath(file));
addFilechange.setInt(2, fileId);
addFilechange.executeUpdate();
}
conn.commit();
// Successfully added the entry. Break out of retry loop.
break retry;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
}
}
/**
* <p>
* Make sure Derby's index cardinality statistics are up to date.
* Otherwise, the optimizer may choose a bad execution strategy for
* some queries. This method should be called if the size of the tables
* has changed significantly.
* </p>
*
* <p>
* This is a workaround for the problems described in
* <a href="https://issues.apache.org/jira/browse/DERBY-269">DERBY-269</a> and
* <a href="https://issues.apache.org/jira/browse/DERBY-3788">DERBY-3788</a>.
* When automatic update of index cardinality statistics has been
* implemented in Derby, the workaround may be removed.
* </p>
*
* <p>
* Note that this method uses a system procedure introduced in Derby 10.5.
* If the Derby version used is less than 10.5, this method is a no-op.
* </p>
*/
private void updateIndexCardinalityStatistics(ConnectionResource conn)
throws SQLException {
DatabaseMetaData dmd = conn.getMetaData();
int major = dmd.getDatabaseMajorVersion();
int minor = dmd.getDatabaseMinorVersion();
if (major > 10 || (major == 10 && minor >= 5)) {
PreparedStatement ps = conn.prepareStatement(
"CALL SYSCS_UTIL.SYSCS_UPDATE_STATISTICS(?, ?, NULL)");
try {
ps.setString(1, SCHEMA);
for (String table : TABLES) {
ps.setString(2, table);
retry:
for (int i = 0;; i++) {
try {
ps.execute();
// Successfully executed statement. Break out of
// retry loop.
break retry;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
conn.commit();
}
} finally {
ps.close();
}
}
}
/**
* Get the id of a repository in the database. If the repository is not
* stored in the database, add it and return its id.
*
* @param conn the connection to the database
* @param repository the repository whose id to get
* @return the id of the repository
*/
private int getRepositoryId(ConnectionResource conn, Repository repository)
throws SQLException {
String reposPath = toUnixPath(repository.getDirectoryName());
PreparedStatement reposIdPS = conn.getStatement(GET_REPOSITORY);
reposIdPS.setString(1, reposPath);
ResultSet reposIdRS = reposIdPS.executeQuery();
try {
if (reposIdRS.next()) {
return reposIdRS.getInt(1);
}
} finally {
reposIdRS.close();
}
// Repository is not in the database. Add it.
PreparedStatement insert =
conn.getStatement(INSERT_REPOSITORY);
insert.setString(1, reposPath);
insert.executeUpdate();
return getGeneratedIntKey(insert);
}
private final static PreparedQuery GET_AUTHORS = new PreparedQuery(
"SELECT NAME, ID FROM AUTHORS WHERE REPOSITORY = ?");
private final static InsertQuery ADD_AUTHOR = new InsertQuery(
"INSERT INTO AUTHORS (REPOSITORY, NAME) VALUES (?,?)");
/**
* Get a map from author names to their ids in the database. The authors
* that are not in the database are added to it.
*
* @param conn the connection to the database
* @param history the history to get the author names from
* @param reposId the id of the repository
* @return a map from author names to author ids
*/
private Map<String, Integer> getAuthors(
ConnectionResource conn, History history, int reposId)
throws SQLException {
HashMap<String, Integer> map = new HashMap<String, Integer>();
PreparedStatement ps = conn.getStatement(GET_AUTHORS);
ps.setInt(1, reposId);
ResultSet rs = ps.executeQuery();
try {
while (rs.next()) {
map.put(rs.getString(1), rs.getInt(2));
}
} finally {
rs.close();
}
PreparedStatement insert = conn.getStatement(ADD_AUTHOR);
insert.setInt(1, reposId);
for (HistoryEntry entry : history.getHistoryEntries()) {
String author = entry.getAuthor();
if (!map.containsKey(author)) {
insert.setString(2, author);
insert.executeUpdate();
int id = getGeneratedIntKey(insert);
map.put(author, id);
}
}
return map;
}
private static PreparedQuery GET_FILES = new PreparedQuery(
"SELECT PATH, ID FROM FILES WHERE REPOSITORY = ?");
private static InsertQuery INSERT_FILE = new InsertQuery(
"INSERT INTO FILES(REPOSITORY, PATH) VALUES (?,?)");
/**
* Get a map from file names to their ids in the database. The files
* that are not in the database are added to it.
*
* @param conn the connection to the database
* @param history the history to get the file names from
* @param reposId the id of the repository
* @return a map from file names to file ids
*/
private Map<String, Integer> getFiles(
ConnectionResource conn, History history, int reposId)
throws SQLException {
Map<String, Integer> map = new HashMap<String, Integer>();
PreparedStatement ps = conn.getStatement(GET_FILES);
ps.setInt(1, reposId);
ResultSet rs = ps.executeQuery();
try {
while (rs.next()) {
map.put(rs.getString(1), rs.getInt(2));
}
} finally {
rs.close();
}
PreparedStatement insert = conn.getStatement(INSERT_FILE);
insert.setInt(1, reposId);
for (HistoryEntry entry : history.getHistoryEntries()) {
for (String file : entry.getFiles()) {
String path = toUnixPath(file);
if (!map.containsKey(path)) {
insert.setString(2, path);
insert.executeUpdate();
map.put(path, getGeneratedIntKey(insert));
}
}
}
return map;
}
/**
* Return the integer key generated by the previous execution of a
* statement. The key should be a single INTEGER, and the statement
* should insert exactly one row, so there should be only one key.
* @param stmt a statement that has just inserted a row
* @return the integer key for the newly inserted row, or {@code null}
* if there is no key
*/
private Integer getGeneratedIntKey(Statement stmt) throws SQLException {
ResultSet keys = stmt.getGeneratedKeys();
try {
if (keys.next()) {
return keys.getInt(1);
} else {
return null;
}
} finally {
keys.close();
}
}
private static PreparedQuery GET_LATEST_REVISION = new PreparedQuery(
"SELECT REVISION FROM CHANGESETS WHERE ID = " +
"(SELECT MAX(CS.ID) FROM CHANGESETS CS, REPOSITORIES R " +
"WHERE CS.REPOSITORY = R.ID AND R.PATH = ?)");
public String getLatestCachedRevision(Repository repository)
throws HistoryException {
try {
for (int i = 0;; i++) {
try {
return getLatestRevisionForRepository(repository);
} catch (SQLException sqle) {
handleSQLException(sqle, i);
}
}
} catch (SQLException sqle) {
throw new HistoryException(sqle);
}
}
/**
* Helper for {@link #getLatestCachedRevision(Repository)}.
*/
private String getLatestRevisionForRepository(Repository repository)
throws SQLException {
final ConnectionResource conn =
connectionManager.getConnectionResource();
try {
PreparedStatement ps = conn.getStatement(GET_LATEST_REVISION);
ps.setString(1, toUnixPath(repository.getDirectoryName()));
ResultSet rs = ps.executeQuery(); // NOPMD (we do check next)
try {
return rs.next() ? rs.getString(1) : null;
} finally {
rs.close();
}
} finally {
connectionManager.releaseConnection(conn);
}
}
}
| false | true | private void storeHistory(ConnectionResource conn, History history,
Repository repository) throws SQLException {
Integer reposId = null;
Map<String, Integer> authors = null;
Map<String, Integer> files = null;
PreparedStatement addChangeset = null;
PreparedStatement addFilechange = null;
for (int i = 0;; i++) {
try {
if (reposId == null) {
reposId = getRepositoryId(conn, repository);
conn.commit();
}
if (authors == null) {
authors = getAuthors(conn, history, reposId);
conn.commit();
}
if (files == null) {
files = getFiles(conn, history, reposId);
conn.commit();
}
if (addChangeset == null) {
addChangeset = conn.getStatement(ADD_CHANGESET);
}
if (addFilechange == null) {
addFilechange = conn.getStatement(ADD_FILECHANGE);
}
// Success! Break out of the loop.
break;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
addChangeset.setInt(1, reposId);
// getHistoryEntries() returns the entries in reverse chronological
// order, but we want to insert them in chronological order so that
// their auto-generated identity column can be used as a chronological
// ordering column. Otherwise, incremental updates will make the
// identity column unusable for chronological ordering. So therefore
// we walk the list backwards.
List<HistoryEntry> entries = history.getHistoryEntries();
for (ListIterator<HistoryEntry> it =
entries.listIterator(entries.size());
it.hasPrevious();) {
retry:
for (int i = 0;; i++) {
try {
HistoryEntry entry = it.previous();
addChangeset.setString(2, entry.getRevision());
addChangeset.setInt(3, authors.get(entry.getAuthor()));
addChangeset.setTimestamp(4,
new Timestamp(entry.getDate().getTime()));
addChangeset.setString(5, entry.getMessage());
addChangeset.executeUpdate();
int changesetId = getGeneratedIntKey(addChangeset);
addFilechange.setInt(1, changesetId);
for (String file : entry.getFiles()) {
int fileId = files.get(toUnixPath(file));
addFilechange.setInt(2, fileId);
addFilechange.executeUpdate();
}
conn.commit();
// Successfully added the entry. Break out of retry loop.
break retry;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
}
}
| private void storeHistory(ConnectionResource conn, History history,
Repository repository) throws SQLException {
Integer reposId = null;
Map<String, Integer> authors = null;
Map<String, Integer> files = null;
PreparedStatement addChangeset = null;
PreparedStatement addFilechange = null;
for (int i = 0;; i++) {
try {
if (reposId == null) {
reposId = getRepositoryId(conn, repository);
conn.commit();
}
if (authors == null) {
authors = getAuthors(conn, history, reposId);
conn.commit();
}
if (files == null) {
files = getFiles(conn, history, reposId);
conn.commit();
}
if (addChangeset == null) {
addChangeset = conn.getStatement(ADD_CHANGESET);
}
if (addFilechange == null) {
addFilechange = conn.getStatement(ADD_FILECHANGE);
}
// Success! Break out of the loop.
break;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
addChangeset.setInt(1, reposId);
// getHistoryEntries() returns the entries in reverse chronological
// order, but we want to insert them in chronological order so that
// their auto-generated identity column can be used as a chronological
// ordering column. Otherwise, incremental updates will make the
// identity column unusable for chronological ordering. So therefore
// we walk the list backwards.
List<HistoryEntry> entries = history.getHistoryEntries();
for (ListIterator<HistoryEntry> it =
entries.listIterator(entries.size());
it.hasPrevious();) {
HistoryEntry entry = it.previous();
retry:
for (int i = 0;; i++) {
try {
addChangeset.setString(2, entry.getRevision());
addChangeset.setInt(3, authors.get(entry.getAuthor()));
addChangeset.setTimestamp(4,
new Timestamp(entry.getDate().getTime()));
addChangeset.setString(5, entry.getMessage());
addChangeset.executeUpdate();
int changesetId = getGeneratedIntKey(addChangeset);
addFilechange.setInt(1, changesetId);
for (String file : entry.getFiles()) {
int fileId = files.get(toUnixPath(file));
addFilechange.setInt(2, fileId);
addFilechange.executeUpdate();
}
conn.commit();
// Successfully added the entry. Break out of retry loop.
break retry;
} catch (SQLException sqle) {
handleSQLException(sqle, i);
conn.rollback();
}
}
}
}
|
diff --git a/fontes/GACCore/src/br/com/sw2/gac/util/ObjectUtils.java b/fontes/GACCore/src/br/com/sw2/gac/util/ObjectUtils.java
index 3e67e2a..23a804f 100644
--- a/fontes/GACCore/src/br/com/sw2/gac/util/ObjectUtils.java
+++ b/fontes/GACCore/src/br/com/sw2/gac/util/ObjectUtils.java
@@ -1,830 +1,830 @@
package br.com.sw2.gac.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import br.com.sw2.gac.modelo.AplicaMedico;
import br.com.sw2.gac.modelo.AplicaMedicoPK;
import br.com.sw2.gac.modelo.CID;
import br.com.sw2.gac.modelo.Cliente;
import br.com.sw2.gac.modelo.ClienteDispositivo;
import br.com.sw2.gac.modelo.ClienteDispositivoPK;
import br.com.sw2.gac.modelo.Contato;
import br.com.sw2.gac.modelo.Contrato;
import br.com.sw2.gac.modelo.Dispositivo;
import br.com.sw2.gac.modelo.FormaComunica;
import br.com.sw2.gac.modelo.HistDispositivo;
import br.com.sw2.gac.modelo.HistDispositivoPK;
import br.com.sw2.gac.modelo.PacoteServico;
import br.com.sw2.gac.modelo.Parametro;
import br.com.sw2.gac.modelo.SMS;
import br.com.sw2.gac.modelo.Script;
import br.com.sw2.gac.modelo.TipoDoenca;
import br.com.sw2.gac.modelo.Tratamento;
import br.com.sw2.gac.modelo.Usuario;
import br.com.sw2.gac.tools.TipoDispositivo;
import br.com.sw2.gac.vo.ClienteVO;
import br.com.sw2.gac.vo.ContatoVO;
import br.com.sw2.gac.vo.ContratoVO;
import br.com.sw2.gac.vo.DispositivoVO;
import br.com.sw2.gac.vo.DoencaVO;
import br.com.sw2.gac.vo.FormaContatoVO;
import br.com.sw2.gac.vo.HistDispositivoVO;
import br.com.sw2.gac.vo.PacoteServicoVO;
import br.com.sw2.gac.vo.ParametroVO;
import br.com.sw2.gac.vo.PerfilVO;
import br.com.sw2.gac.vo.ScriptVO;
import br.com.sw2.gac.vo.SmsVO;
import br.com.sw2.gac.vo.TipoDoencaVO;
import br.com.sw2.gac.vo.TratamentoVO;
import br.com.sw2.gac.vo.UsuarioVO;
/**
* <b>Descrição: Classe para manipulação de objetos.</b> <br>
* .
* @author: SW2
* @version 1.0 Copyright 2012 SmartAngel.
*/
public final class ObjectUtils {
/** Constante GET. */
private static final String GET = "get";
/**
* Construtor Padrao Instancia um novo objeto ObjectUtils.
*/
private ObjectUtils() {
super();
}
/**
* Realiza verificação sobre o argumento <i>object</i>, se este argumento for nulo retorna
* Boolean.TRUE, caso contrário Boolean.FALSE.
* @param object the object
* @return Boolean
* @see
*/
public static Boolean isNull(Object object) {
return (object == null);
}
/**
* Realiza verificação sobre o argumento <i>object</i>, se este argumento n�o for nulo retorna
* Boolean.TRUE, caso contr�rio Boolean.FALSE.
* @param object the object
* @return Boolean
* @see
*/
public static Boolean isNotNull(Object object) {
return (object != null);
}
/**
* Recupera o nome do método accessor Get.
* @param field the field
* @return java.lang.String Getter
* @see
*/
public static String getAccessorGetterName(Field field) {
return (getAccessorName(field, GET));
}
/**
* Recupera o nome do método accessor Get.
* @param name the name
* @return java.lang.String Getter
* @see
*/
public static String getAccessorGetterName(String name) {
return (GET + String.valueOf(name.charAt(0)).toUpperCase() + name.substring(1));
}
/**
* Recupera o nome do método conforme tipo do método acessor Get ou Set.
* @param field the field
* @param accessorType the accessor type
* @return java.lang.String Getter
* @see
*/
private static String getAccessorName(Field field, String accessorType) {
return (accessorType + String.valueOf(field.getName().charAt(0)).toUpperCase() + field
.getName().substring(1));
}
/**
* Realiza a invocação ao método <i>methodName</i> e objeto <i>object</i> informado.
* @param methodName Nome do método.
* @param object Objeto a qual o método ser� executado.
* @param parameterTypes Tipo dos par�metros para os argumentos do método.
* @param args Argumentos do método.
* @return java.lang.Object Valor retornado quando executado o método.
* @throws Exception the exception
* @see
*/
public static Object invokeMethod(String methodName, Object object, Class<?>[] parameterTypes,
Object[] args) throws Exception {
try {
Method method = object.getClass().getMethod(methodName, parameterTypes);
return (method.invoke(object, args));
} catch (Exception exception) {
throw (exception);
}
}
/**
* Realiza a invocação ao método <i>methodName</i> e objeto <i>object</i> informado. Este método
* deve seguir a especificação Java para métodos getters.
* @param field the field
* @param object Objeto a qual o método ser� executado.
* @return java.lang.Object Valor retornado quando executado o método.
* @throws Exception the exception
* @see
*/
public static Object invokeGetterMethod(Field field, Object object) throws Exception {
return (ObjectUtils.invokeMethod(ObjectUtils.getAccessorGetterName(field), object,
new Class[0], new Object[0]));
}
/**
* Recupera a representação do método setter do atributo informado pelo argumento <i>field</i>.
* @param field the field
* @param object the object
* @return valor do atributo 'getterMethod'
* @throws Exception the exception
* @see
*/
public static Method getGetterMethod(Field field, Object object) throws Exception {
return (object.getClass().getDeclaredMethod(ObjectUtils.getAccessorGetterName(field),
new Class<?>[0]));
}
/**
* Verifica se o valor informado <i>value</i> é uma instancia do tipo informado pelo argumento
* <i>classType</i>.
* @param value the value
* @param classType the class type
* @return boolean
* @see
*/
public static Boolean instanceOf(Object value, Class<?> classType) {
return ((!ObjectUtils.isNull(value)) && (classType.isInstance(value)));
}
/**
* Recupera o valor da propriedade do objeto.
* @param propertyName Nome da propriedade do objeto a ser recuperado o valor.
* @param object Objeto a ser extraido o valor da propriedade.
* @return valor do atributo 'propertyValue'
* @throws Exception the exception
* @see
*/
public static Object getPropertyValue(String propertyName, Object object) throws Exception {
Object parentObject = object;
String token = null;
Object propertyValue = null;
for (StringTokenizer tokens = new StringTokenizer(propertyName, "."); tokens
.hasMoreTokens();) {
token = tokens.nextToken();
try {
propertyValue = ObjectUtils.getPropertyValue(parentObject.getClass()
.getDeclaredField(token), parentObject);
} catch (NoSuchFieldException exception) {
propertyValue = ObjectUtils.invokeMethod(ObjectUtils.getAccessorGetterName(token),
parentObject, new Class<?>[0], new Object[0]);
}
if (tokens.hasMoreTokens()) {
parentObject = propertyValue;
}
}
return (propertyValue);
}
/**
* Recupera o valor da propriedade do objeto.
* @param property the property
* @param object the object
* @return valor do atributo 'propertyValue'
* @throws Exception the exception
* @see
*/
public static Object getPropertyValue(Field property, Object object) throws Exception {
Object value = null;
try {
value = property.get(object);
} catch (Exception exception) {
return (ObjectUtils.invokeGetterMethod(property, object));
}
return (value);
}
/**
* Nome: getResourceAsProperties Recupera o valor do atributo 'resourceAsProperties'.
* @param resourceName the resource name
* @return valor do atributo 'resourceAsProperties'
* @throws Exception the exception
* @see
*/
@SuppressWarnings("unchecked")
public static Properties getResourceAsProperties(String resourceName) throws Exception {
if (null == resourceName) {
throw (new IllegalArgumentException("O valor informado pelo argumento "
+ "[resourceName] Não pode ser nulo"));
}
InputStream inputStream = ClassLoaderUtils.getDefaultClassLoader().getResourceAsStream(
resourceName);
Properties properties = new Properties();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String key;
StringTokenizer map = null;
String propertyKey = null;
Object value = null;
List<String> list = null;
while ((key = in.readLine()) != null) {
key = key.trim();
if (("".equals(key)) || ("#".equals(String.valueOf(key.charAt(0))))) {
continue;
}
map = new StringTokenizer(key, "=");
if (map.countTokens() == 2) {
propertyKey = map.nextToken().trim();
if (properties.containsKey(propertyKey)) {
Object propertyValue = properties.get(propertyKey);
if (!(propertyValue instanceof List)) {
list = new ArrayList<String>();
list.add(propertyValue.toString());
properties.remove(propertyKey);
} else {
list = (List<String>) propertyValue;
}
list.add(map.nextToken().trim());
value = list;
} else {
value = map.nextToken().trim();
}
properties.put(propertyKey, value);
}
}
return (properties);
}
/**
* Nome: parse Converte o objeto ScriptVO em uma entity Script.
* @param vo the vo
* @return script
* @see
*/
public static Script parse(ScriptVO vo) {
Script entity = new Script();
entity.setIdScript(vo.getIdScript());
entity.setNmTitulo(vo.getTituloScript());
entity.setDsDescricao(vo.getDescricaoScript());
entity.setDsProcesso(vo.getProcessoSeguir());
entity.setDtInicioValidade(vo.getDtInicioValidade());
entity.setDtFinalValidade(vo.getDtFinalValidade());
return entity;
}
/**
* Nome: parse Converte uma entity Script em um objeto ScriptVO.
* @param entity the entity
* @return script vo
* @see
*/
public static ScriptVO parse(Script entity) {
ScriptVO vo = new ScriptVO();
vo.setIdScript(entity.getIdScript());
vo.setTituloScript(entity.getNmTitulo());
vo.setDescricaoScript(entity.getDsDescricao());
vo.setProcessoSeguir(entity.getDsProcesso());
vo.setDtInicioValidade(entity.getDtInicioValidade());
vo.setDtFinalValidade(entity.getDtFinalValidade());
return vo;
}
/**
* Nome: parse Converte uma entity SMS em um objeto SmsVO.
* @param entity the entity
* @return sms vo
* @see
*/
public static SmsVO parse(SMS entity) {
SmsVO vo = new SmsVO();
vo.setIdSms(entity.getIdSMS());
vo.setTitulo(entity.getTpMensagem());
vo.setTexto(entity.getDsMensagem());
vo.setDtInicioValidade(entity.getDtInicioValidade());
vo.setDtTerminoValidade(entity.getDtTerminoValidade());
return vo;
}
/**
* Nome: parse Converte o objeto SmsVO em uma entity SMS.
* @param vo the vo
* @return sms
* @see
*/
public static SMS parse(SmsVO vo) {
SMS entity = new SMS();
entity.setTpMensagem(vo.getTitulo());
entity.setDsMensagem(vo.getTexto());
entity.setDtInicioValidade(vo.getDtInicioValidade());
entity.setDtTerminoValidade(vo.getDtTerminoValidade());
return entity;
}
/**
* Nome: parse Converte o objeto UsuarioVO em uma entity Usuario.
* @param vo the vo
* @return usuario
* @see
*/
public static Usuario parse(UsuarioVO vo) {
Usuario entity = null;
if (null != vo) {
String senhaCriptografada = null;
if (null != vo.getSenha()) {
senhaCriptografada = StringUtil.encriptarTexto(vo.getSenha());
}
entity = new Usuario();
entity.setSenha(senhaCriptografada);
entity.setLogin(vo.getLogin());
entity.setNmUsuario(vo.getLogin());
if (null != vo.getPerfil() && null != vo.getPerfil().getIdPerfil()) {
entity.setCdPerfil(vo.getPerfil().getIdPerfil());
}
}
return entity;
}
/**
* Nome: parse Converte uma entity Usuario em um objeto UsuarioVO.
* @param entity the entity
* @return usuario vo
* @see
*/
public static UsuarioVO parse(Usuario entity) {
UsuarioVO vo = new UsuarioVO();
vo.setSenha(entity.getSenha());
vo.setLogin(entity.getLogin());
vo.setNomeUsuario(entity.getLogin());
PerfilVO perfil = new PerfilVO();
perfil.setIdPerfil(entity.getCdPerfil());
vo.setPerfil(perfil);
return vo;
}
/**
* Nome: Converte DispositivoVO em Entity.
* @param dispositivo vo
* @return Dispositivo entity
* @see
*/
public static Dispositivo parse(DispositivoVO dispositivo) {
Dispositivo entity = new Dispositivo();
entity.setIdDispositivo(dispositivo.getIdDispositivo());
entity.setTpEstado(dispositivo.getEstadoAtual());
entity.setTpDispositivo(dispositivo.getTipoDispositivo());
entity.setDtaEntrada(dispositivo.getDataEntrada());
entity.setDtaFabrica(dispositivo.getDataFabricacao());
entity.setDtaProximaManut(dispositivo.getDataProximaManutencao());
entity.setDtaSucata(dispositivo.getDataSucata());
entity.setLocal(dispositivo.getLocal());
Usuario usuario = new Usuario();
usuario.setLogin(dispositivo.getUsuario().getLogin());
entity.setLogin(usuario);
return entity;
}
/**
* Nome: Converte Entity em DispositivoVO.
* @param entity Dispositivo
* @return DispositivoVO vo
* @see
*/
public static DispositivoVO parse(Dispositivo entity) {
DispositivoVO dispositivo = new DispositivoVO();
dispositivo.setIdDispositivo(entity.getIdDispositivo());
dispositivo.setUsuario((UsuarioVO) ObjectUtils.parse(entity.getLogin()));
dispositivo.setEstadoAtual(entity.getTpEstado());
dispositivo.setTipoDispositivo(entity.getTpDispositivo());
dispositivo.setDataEntrada(entity.getDtaEntrada());
dispositivo.setDataFabricacao(entity.getDtaFabrica());
dispositivo.setDataProximaManutencao(entity.getDtaProximaManut());
dispositivo.setDataSucata(entity.getDtaSucata());
dispositivo.setLocal(entity.getLocal());
return dispositivo;
}
/**
* Nome: Converte Entity em PacoteServicoVO.
* @param entity PacoteServico
* @return PacoteServicoVO vo
* @see
*/
public static PacoteServicoVO parse(PacoteServico entity) {
PacoteServicoVO pacoteServico = new PacoteServicoVO();
pacoteServico.setIdPacote(entity.getIdServico());
pacoteServico.setDescricao(entity.getDsServico());
pacoteServico.setPreco(entity.getPrcMensal());
pacoteServico.setTitulo(entity.getDsTitulo());
pacoteServico.setDataInicioValidade(entity.getDtInicioValidade());
pacoteServico.setDataFinalValidade(entity.getDtFinalValidade());
return pacoteServico;
}
/**
* Nome: parse Parses the.
* @param vo the vo
* @return pacote servico
* @see
*/
public static PacoteServico parse(PacoteServicoVO vo) {
PacoteServico entity = new PacoteServico();
entity.setIdServico(vo.getIdPacote());
entity.setDsTitulo(vo.getTitulo());
entity.setDsServico(vo.getDescricao());
entity.setPrcMensal(vo.getPreco());
entity.setDtInicioValidade(vo.getDataInicioValidade());
entity.setDtFinalValidade(vo.getDataFinalValidade());
return entity;
}
/**
* Nome: Converte Entity em ContratoVO.
* @param entity Contrato
* @return ContratoVO contrato
* @see
*/
public static ContratoVO parse(Contrato entity) {
ContratoVO contrato = new ContratoVO();
contrato.setNumeroContrato(entity.getNmContrato());
contrato.setCpfContratante(entity.getNmCPFContratante());
contrato.setDtFinalValidade(entity.getDtFinalValidade());
contrato.setDtInicioValidade(entity.getDtInicioValidade());
contrato.setDtSuspensao(entity.getDtSuspensao());
contrato.setIdServico(entity.getIdServico().getIdServico());
contrato.setRgContratante(entity.getNmRGContratante());
contrato.setNomeContratante(entity.getNmNomeContratante());
contrato.setUsuario(parse(entity.getLogin()));
contrato.setDtProxAtual(contrato.getDtProxAtual());
return contrato;
}
/**
* Nome: Converte um vo de Contrato em uma entity.
* @param vo ContratoVO
* @return Contrato entity
* @see
*/
public static Contrato parse(ContratoVO vo) {
Contrato entity = new Contrato();
entity.setNmContrato(vo.getNumeroContrato());
entity.setNmCPFContratante(vo.getCpfContratante());
entity.setDtFinalValidade(vo.getDtFinalValidade());
entity.setDtInicioValidade(vo.getDtInicioValidade());
entity.setDtSuspensao(vo.getDtSuspensao());
PacoteServico pacoteServico = new PacoteServico();
pacoteServico.setIdServico(vo.getPacoteServico().getIdPacote());
entity.setIdServico(pacoteServico);
entity.setNmRGContratante(vo.getRgContratante());
entity.setNmNomeContratante(vo.getNomeContratante());
entity.setLogin(parse(vo.getUsuario()));
entity.setDtProxAtual(vo.getDtProxAtual());
if (null != vo.getCliente()) {
// Apesar de estar mapeado como oneTomany o relacionamento no sistema sera oneToOne.
entity.setClienteList(new ArrayList<Cliente>());
entity.getClienteList().add(ObjectUtils.parse(vo.getCliente()));
}
return entity;
}
/**
* Nome: parse Parses the.
* @param entity the entity
* @return doenca vo
* @see
*/
public static DoencaVO parse(TipoDoenca entity) {
return null;
}
/**
* Nome: Converte Entity em HistDispositivoVO.
* @param histDispositivo vo
* @return HistDispositivo entity
* @see
*/
public static HistDispositivo parse(HistDispositivoVO histDispositivo) {
HistDispositivo entity = new HistDispositivo();
entity.setCdEstadoAnterior(histDispositivo.getEstadoAnterior());
HistDispositivoPK tblhistdispositivoPK = new HistDispositivoPK(
histDispositivo.getDthrMudaEstado(), histDispositivo.getIdDispositivo());
entity.setTblhistdispositivoPK(tblhistdispositivoPK);
entity.setLogin(histDispositivo.getLogin());
return entity;
}
/**
* Nome: Converte HistDispositivoVO em Entity.
* @param entity HistDispositivo
* @return HistDispositivoVO vo
* @see
*/
public static HistDispositivoVO parse(HistDispositivo entity) {
HistDispositivoVO histDispositivo = new HistDispositivoVO();
histDispositivo.setEstadoAnterior(entity.getCdEstadoAnterior());
Dispositivo dispositivo = entity.getDispositivo();
histDispositivo.setDispositivo(ObjectUtils.parse(dispositivo));
histDispositivo.setDthrMudaEstado(entity.getTblhistdispositivoPK().getDthrMudaEstado());
histDispositivo.setIdDispositivo(dispositivo.getIdDispositivo());
histDispositivo.setLogin(entity.getLogin());
return histDispositivo;
}
/**
* Nome: Converte um vo de ParametroVO em uma entity de Parametro Parses the.
* @param vo the parametro
* @return parametro
* @see
*/
public static Parametro parse(ParametroVO vo) {
Parametro entity = new Parametro();
entity.setIdParametro(vo.getIdParametro());
entity.setDiasDados(vo.getDiasDados());
entity.setDiasBemEstar(vo.getDiasBemEstar());
entity.setToleraRotinaCliente(vo.getToleraRotinaCliente());
return entity;
}
/**
* Nome: parse Parses the.
* @param entity the entity
* @return parametro vo
* @see
*/
public static ParametroVO parse(Parametro entity) {
ParametroVO vo = new ParametroVO();
vo.setIdParametro(entity.getIdParametro());
vo.setDiasDados(entity.getDiasDados());
vo.setDiasBemEstar(entity.getDiasBemEstar());
vo.setToleraRotinaCliente(entity.getToleraRotinaCliente());
return vo;
}
/**
* Nome: parse Converte um Vo de cliente em uma entity.
* @param vo the vo
* @return cliente
* @see
*/
public static Cliente parse(ClienteVO vo) {
Cliente entity = new Cliente();
entity.setNmCPFCliente(vo.getCpf());
entity.setNrRG(vo.getRg());
entity.setNmCliente(vo.getNome());
entity.setDsEndereco(vo.getEndereco().getEndereco());
entity.setDsBairro(vo.getEndereco().getBairro());
entity.setDsCidade(vo.getEndereco().getCidade());
entity.setDsCEP(vo.getEndereco().getCep());
entity.setDsEstado(vo.getEndereco().getUf());
entity.setDtNascimento(vo.getDataNascimento());
entity.setTpSexo(Integer.parseInt(vo.getSexo()));
entity.setNmNecessidadeEspecial(vo.getNecessidadeEspecial());
entity.setNmPlanoSaude(vo.getPlanoSaude());
entity.setDsCobertura(vo.getCobertura());
entity.setLogin(parse(vo.getUsuario()));
// Formas de contato com o cliente
entity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
vo.getListaFormaContato(), entity));
// Lista de contatos do cliente
List<Contato> listaContatos = new ArrayList<Contato>();
for (ContatoVO contatoVO : vo.getListaContatos()) {
Contato contatoEntity = parse(contatoVO);
contatoEntity.setLogin(entity.getLogin());
contatoEntity.setNmCPFCliente(entity);
contatoEntity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
contatoVO.getListaFormaContato(), entity));
listaContatos.add(contatoEntity);
}
entity.setContatoList(listaContatos);
// Lsita de dispositivo do cliente
List<ClienteDispositivo> listaClienteDispositivo = new ArrayList<ClienteDispositivo>();
for (DispositivoVO item : vo.getListaDispositivos()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de centrais do cliente
for (DispositivoVO item : vo.getListaCentrais()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setTpDispositivo(TipoDispositivo.CentralEletronica.getValue());
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de doenças
List<CID> listaDoencasCliente = new ArrayList<CID>();
for (DoencaVO item : vo.getListaDoencas()) {
CID doencaEntity = new CID();
doencaEntity.setCdCID(item.getCodigoCID());
listaDoencasCliente.add(doencaEntity);
}
// Lista de tratamentos
List<Tratamento> listaTratamento = new ArrayList<Tratamento>();
if (!CollectionUtils.isEmptyOrNull(vo.getListaTratamentos())) {
for (TratamentoVO item : vo.getListaTratamentos()) {
Tratamento tratamento = new Tratamento();
tratamento.setNomeTrata(item.getNomeTratamento());
tratamento.setDescrTrata(item.getDescricaoTratamento());
tratamento.setTpFrequencia(item.getFrequencia());
tratamento.setHoraInicial(item.getDataHoraInicial());
tratamento.setAplicaMedicoList(new ArrayList<AplicaMedico>());
tratamento.setIdTratamento(item.getIdTratamento());
tratamento.setCliente(entity);
- if (CollectionUtils.isEmptyOrNull(item.getListaHorarios())) {
+ if (!CollectionUtils.isEmptyOrNull(item.getListaHorarios())) {
for (String horario : item.getListaHorarios()) {
Calendar calendar = DateUtil.stringToTime(horario);
AplicaMedico aplicaMedico = new AplicaMedico();
AplicaMedicoPK aplicaMedicopk = new AplicaMedicoPK();
aplicaMedicopk.setHrAplicacao(calendar.getTime());
aplicaMedicopk.setIdTratamento(tratamento.getIdTratamento());
aplicaMedicopk.setNmCPFCliente(entity.getNmCPFCliente());
aplicaMedicopk.setIdTratamento(item.getIdTratamento());
aplicaMedico.setAplicaMedicoPK(aplicaMedicopk);
// horario.setTratamento(tratamento);
tratamento.getAplicaMedicoList().add(aplicaMedico);
}
}
listaTratamento.add(tratamento);
}
}
entity.setCIDList(listaDoencasCliente);
entity.setClienteDispositivoList(listaClienteDispositivo);
entity.setTratamentoList(listaTratamento);
return entity;
}
/**
* Nome: parseListFormaComunica Converte uma List de FormaComunicacaoVO para uma lista de
* FormaComunica.
* @param list the list
* @param entity the entity
* @return list
* @see
*/
private static List<FormaComunica> parseToListFormaComunicacaoEntity(List<FormaContatoVO> list,
Cliente entity) {
List<FormaComunica> listFormaComunica = new ArrayList<FormaComunica>();
for (FormaContatoVO item : list) {
FormaComunica formaComunica = ObjectUtils.parse(item);
formaComunica.setNmCPFCliente(entity);
listFormaComunica.add(formaComunica);
}
return listFormaComunica;
}
/**
* Nome: parse Converte um VO de FormaContato em uma entity.
* @param vo the vo
* @return forma comunica
* @see
*/
public static FormaComunica parse(FormaContatoVO vo) {
FormaComunica entity = new FormaComunica();
if (!StringUtil.isVazio(vo.getTelefone(), true)) {
entity.setFoneContato(vo.getTelefone().replace("-", "").replace("(", "")
.replace(")", ""));
}
entity.setIdFormaComunica(vo.getIdFormaContato());
entity.setMailContato(vo.getEmail());
entity.setTpContato(vo.getTipoContato());
return entity;
}
/**
* Nome: parse Converte uma entity CID em um objeto DoencaVO.
* @param entity the entity
* @return script vo
* @see
*/
public static DoencaVO parse(CID entity) {
DoencaVO vo = new DoencaVO();
vo.setCodigoCID(entity.getCdCID());
vo.setNomeDoenca(entity.getNmDoenca());
if (null != entity.getCdTipoDoenca()) {
TipoDoencaVO tipoDoenca = new TipoDoencaVO();
tipoDoenca.setCatFinal(entity.getCdTipoDoenca().getCatFinal());
tipoDoenca.setCatInic(entity.getCdTipoDoenca().getCatInic());
tipoDoenca.setCdTipoDoenca(entity.getCdTipoDoenca().getCdTipoDoenca());
tipoDoenca.setDsTipoDoenca(entity.getCdTipoDoenca().getDsTipoDoenca());
tipoDoenca.setNmCapitulo(entity.getCdTipoDoenca().getNmCapitulo());
vo.setTipoDoenca(tipoDoenca);
}
return vo;
}
/**
* Nome: parse parse Converte uma entity Contato em um objeto ContatoVO.
* @param vo the vo
* @return contato
* @see
*/
public static Contato parse(ContatoVO vo) {
Contato entity = new Contato();
entity.setNomeContato(vo.getNome());
entity.setGrauParentesco(vo.getGrauParentesco());
if (null != vo.getEndereco()) {
entity.setEndContato(vo.getEndereco().getEndereco());
entity.setBaiContato(vo.getEndereco().getBairro());
entity.setCidContato(vo.getEndereco().getCidade());
entity.setCepContato(vo.getEndereco().getCep());
}
if (vo.isContratante()) {
entity.setContratante("1");
} else {
entity.setContratante("0");
}
entity.setGrauParentesco(vo.getGrauParentesco());
entity.setSqaChamada(vo.getSqaChamada());
if (!CollectionUtils.isEmptyOrNull(vo.getListaFormaContato())) {
List<FormaComunica> listaFormaComunica = new ArrayList<FormaComunica>();
for (FormaContatoVO item : vo.getListaFormaContato()) {
FormaComunica formaComunica = parse(item);
listaFormaComunica.add(formaComunica);
}
}
return entity;
}
}
| true | true | public static Cliente parse(ClienteVO vo) {
Cliente entity = new Cliente();
entity.setNmCPFCliente(vo.getCpf());
entity.setNrRG(vo.getRg());
entity.setNmCliente(vo.getNome());
entity.setDsEndereco(vo.getEndereco().getEndereco());
entity.setDsBairro(vo.getEndereco().getBairro());
entity.setDsCidade(vo.getEndereco().getCidade());
entity.setDsCEP(vo.getEndereco().getCep());
entity.setDsEstado(vo.getEndereco().getUf());
entity.setDtNascimento(vo.getDataNascimento());
entity.setTpSexo(Integer.parseInt(vo.getSexo()));
entity.setNmNecessidadeEspecial(vo.getNecessidadeEspecial());
entity.setNmPlanoSaude(vo.getPlanoSaude());
entity.setDsCobertura(vo.getCobertura());
entity.setLogin(parse(vo.getUsuario()));
// Formas de contato com o cliente
entity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
vo.getListaFormaContato(), entity));
// Lista de contatos do cliente
List<Contato> listaContatos = new ArrayList<Contato>();
for (ContatoVO contatoVO : vo.getListaContatos()) {
Contato contatoEntity = parse(contatoVO);
contatoEntity.setLogin(entity.getLogin());
contatoEntity.setNmCPFCliente(entity);
contatoEntity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
contatoVO.getListaFormaContato(), entity));
listaContatos.add(contatoEntity);
}
entity.setContatoList(listaContatos);
// Lsita de dispositivo do cliente
List<ClienteDispositivo> listaClienteDispositivo = new ArrayList<ClienteDispositivo>();
for (DispositivoVO item : vo.getListaDispositivos()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de centrais do cliente
for (DispositivoVO item : vo.getListaCentrais()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setTpDispositivo(TipoDispositivo.CentralEletronica.getValue());
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de doenças
List<CID> listaDoencasCliente = new ArrayList<CID>();
for (DoencaVO item : vo.getListaDoencas()) {
CID doencaEntity = new CID();
doencaEntity.setCdCID(item.getCodigoCID());
listaDoencasCliente.add(doencaEntity);
}
// Lista de tratamentos
List<Tratamento> listaTratamento = new ArrayList<Tratamento>();
if (!CollectionUtils.isEmptyOrNull(vo.getListaTratamentos())) {
for (TratamentoVO item : vo.getListaTratamentos()) {
Tratamento tratamento = new Tratamento();
tratamento.setNomeTrata(item.getNomeTratamento());
tratamento.setDescrTrata(item.getDescricaoTratamento());
tratamento.setTpFrequencia(item.getFrequencia());
tratamento.setHoraInicial(item.getDataHoraInicial());
tratamento.setAplicaMedicoList(new ArrayList<AplicaMedico>());
tratamento.setIdTratamento(item.getIdTratamento());
tratamento.setCliente(entity);
if (CollectionUtils.isEmptyOrNull(item.getListaHorarios())) {
for (String horario : item.getListaHorarios()) {
Calendar calendar = DateUtil.stringToTime(horario);
AplicaMedico aplicaMedico = new AplicaMedico();
AplicaMedicoPK aplicaMedicopk = new AplicaMedicoPK();
aplicaMedicopk.setHrAplicacao(calendar.getTime());
aplicaMedicopk.setIdTratamento(tratamento.getIdTratamento());
aplicaMedicopk.setNmCPFCliente(entity.getNmCPFCliente());
aplicaMedicopk.setIdTratamento(item.getIdTratamento());
aplicaMedico.setAplicaMedicoPK(aplicaMedicopk);
// horario.setTratamento(tratamento);
tratamento.getAplicaMedicoList().add(aplicaMedico);
}
}
listaTratamento.add(tratamento);
}
}
entity.setCIDList(listaDoencasCliente);
entity.setClienteDispositivoList(listaClienteDispositivo);
entity.setTratamentoList(listaTratamento);
return entity;
}
| public static Cliente parse(ClienteVO vo) {
Cliente entity = new Cliente();
entity.setNmCPFCliente(vo.getCpf());
entity.setNrRG(vo.getRg());
entity.setNmCliente(vo.getNome());
entity.setDsEndereco(vo.getEndereco().getEndereco());
entity.setDsBairro(vo.getEndereco().getBairro());
entity.setDsCidade(vo.getEndereco().getCidade());
entity.setDsCEP(vo.getEndereco().getCep());
entity.setDsEstado(vo.getEndereco().getUf());
entity.setDtNascimento(vo.getDataNascimento());
entity.setTpSexo(Integer.parseInt(vo.getSexo()));
entity.setNmNecessidadeEspecial(vo.getNecessidadeEspecial());
entity.setNmPlanoSaude(vo.getPlanoSaude());
entity.setDsCobertura(vo.getCobertura());
entity.setLogin(parse(vo.getUsuario()));
// Formas de contato com o cliente
entity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
vo.getListaFormaContato(), entity));
// Lista de contatos do cliente
List<Contato> listaContatos = new ArrayList<Contato>();
for (ContatoVO contatoVO : vo.getListaContatos()) {
Contato contatoEntity = parse(contatoVO);
contatoEntity.setLogin(entity.getLogin());
contatoEntity.setNmCPFCliente(entity);
contatoEntity.setFormaComunicaList(parseToListFormaComunicacaoEntity(
contatoVO.getListaFormaContato(), entity));
listaContatos.add(contatoEntity);
}
entity.setContatoList(listaContatos);
// Lsita de dispositivo do cliente
List<ClienteDispositivo> listaClienteDispositivo = new ArrayList<ClienteDispositivo>();
for (DispositivoVO item : vo.getListaDispositivos()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de centrais do cliente
for (DispositivoVO item : vo.getListaCentrais()) {
ClienteDispositivo cd = new ClienteDispositivo();
cd.setCliente(entity);
ClienteDispositivoPK cdpk = new ClienteDispositivoPK();
cdpk.setIdDispositivo(item.getIdDispositivo());
cdpk.setNmCPFCliente(entity.getNmCPFCliente());
cd.setClienteDispositivoPK(cdpk);
Dispositivo dispEntity = new Dispositivo();
dispEntity.setTpDispositivo(TipoDispositivo.CentralEletronica.getValue());
dispEntity.setIdDispositivo(item.getIdDispositivo());
cd.setDispositivo(dispEntity);
listaClienteDispositivo.add(cd);
}
// Lista de doenças
List<CID> listaDoencasCliente = new ArrayList<CID>();
for (DoencaVO item : vo.getListaDoencas()) {
CID doencaEntity = new CID();
doencaEntity.setCdCID(item.getCodigoCID());
listaDoencasCliente.add(doencaEntity);
}
// Lista de tratamentos
List<Tratamento> listaTratamento = new ArrayList<Tratamento>();
if (!CollectionUtils.isEmptyOrNull(vo.getListaTratamentos())) {
for (TratamentoVO item : vo.getListaTratamentos()) {
Tratamento tratamento = new Tratamento();
tratamento.setNomeTrata(item.getNomeTratamento());
tratamento.setDescrTrata(item.getDescricaoTratamento());
tratamento.setTpFrequencia(item.getFrequencia());
tratamento.setHoraInicial(item.getDataHoraInicial());
tratamento.setAplicaMedicoList(new ArrayList<AplicaMedico>());
tratamento.setIdTratamento(item.getIdTratamento());
tratamento.setCliente(entity);
if (!CollectionUtils.isEmptyOrNull(item.getListaHorarios())) {
for (String horario : item.getListaHorarios()) {
Calendar calendar = DateUtil.stringToTime(horario);
AplicaMedico aplicaMedico = new AplicaMedico();
AplicaMedicoPK aplicaMedicopk = new AplicaMedicoPK();
aplicaMedicopk.setHrAplicacao(calendar.getTime());
aplicaMedicopk.setIdTratamento(tratamento.getIdTratamento());
aplicaMedicopk.setNmCPFCliente(entity.getNmCPFCliente());
aplicaMedicopk.setIdTratamento(item.getIdTratamento());
aplicaMedico.setAplicaMedicoPK(aplicaMedicopk);
// horario.setTratamento(tratamento);
tratamento.getAplicaMedicoList().add(aplicaMedico);
}
}
listaTratamento.add(tratamento);
}
}
entity.setCIDList(listaDoencasCliente);
entity.setClienteDispositivoList(listaClienteDispositivo);
entity.setTratamentoList(listaTratamento);
return entity;
}
|
diff --git a/java/src/main/java/tripleplay/platform/JavaTPPlatform.java b/java/src/main/java/tripleplay/platform/JavaTPPlatform.java
index 2cba3a0c..3f4779cd 100644
--- a/java/src/main/java/tripleplay/platform/JavaTPPlatform.java
+++ b/java/src/main/java/tripleplay/platform/JavaTPPlatform.java
@@ -1,87 +1,89 @@
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.platform;
import java.awt.Dimension;
import java.awt.Canvas;
import javax.swing.JFrame;
import org.lwjgl.opengl.Display;
import playn.core.Keyboard;
import playn.java.JavaPlatform;
import react.Value;
import react.ValueView;
/**
* Implements Java-specific TriplePlay services.
*/
public class JavaTPPlatform extends TPPlatform
{
/** Registers the IOS TriplePlay platform. */
public static JavaTPPlatform register (JavaPlatform platform, JavaPlatform.Config config) {
JavaTPPlatform instance = new JavaTPPlatform(platform, config);
TPPlatform.register(instance);
return instance;
}
protected JavaTPPlatform (JavaPlatform platform, JavaPlatform.Config config) {
_platform = platform;
_frame = new JFrame("Game");
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new Canvas();
canvas.setPreferredSize(new Dimension(config.width, config.height));
_frame.getContentPane().add(canvas);
- _frame.pack();
+ // NOTE: This order is important. Resizability changes window decorations on some
+ // platforms/themes and we need the packing to happen last to take that into account.
_frame.setResizable(false);
_frame.setVisible(true);
+ _frame.pack();
try {
Display.setParent(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override public boolean hasNativeTextFields () {
return true;
}
@Override public NativeTextField createNativeTextField () {
return new JavaNativeTextField(_frame.getLayeredPane());
}
@Override public void setVirtualKeyboardController (VirtualKeyboardController ctrl) {
// nada, no virtual keyboard
}
@Override public void setVirtualKeyboardListener (Keyboard.Listener listener) {
// nada, no virtual keyboard
}
@Override public ValueView<Boolean> virtualKeyboardActive () {
return _false;
}
/**
* Sets the title of the window.
*
* @param title the window title
*/
public void setTitle (String title) {
_frame.setTitle(title);
}
/** The Java platform with which this TPPlatform was registered. */
protected JavaPlatform _platform;
protected JFrame _frame;
protected final Value<Boolean> _false = Value.create(false);
}
| false | true | protected JavaTPPlatform (JavaPlatform platform, JavaPlatform.Config config) {
_platform = platform;
_frame = new JFrame("Game");
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new Canvas();
canvas.setPreferredSize(new Dimension(config.width, config.height));
_frame.getContentPane().add(canvas);
_frame.pack();
_frame.setResizable(false);
_frame.setVisible(true);
try {
Display.setParent(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
| protected JavaTPPlatform (JavaPlatform platform, JavaPlatform.Config config) {
_platform = platform;
_frame = new JFrame("Game");
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new Canvas();
canvas.setPreferredSize(new Dimension(config.width, config.height));
_frame.getContentPane().add(canvas);
// NOTE: This order is important. Resizability changes window decorations on some
// platforms/themes and we need the packing to happen last to take that into account.
_frame.setResizable(false);
_frame.setVisible(true);
_frame.pack();
try {
Display.setParent(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java b/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java
index 2f844752..cf75f37f 100644
--- a/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java
+++ b/src/main/java/org/multibit/viewsystem/swing/MultiBitFrame.java
@@ -1,1165 +1,1165 @@
/**
* Copyright 2012 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit.viewsystem.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigInteger;
import java.util.Timer;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
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.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import org.multibit.Localiser;
import org.multibit.controller.MultiBitController;
import org.multibit.exchange.TickerTimerTask;
import org.multibit.message.Message;
import org.multibit.message.MessageManager;
import org.multibit.model.MultiBitModel;
import org.multibit.model.PerWalletModelData;
import org.multibit.model.StatusEnum;
import org.multibit.model.WalletBusyListener;
import org.multibit.model.WalletMajorVersion;
import org.multibit.platform.GenericApplication;
import org.multibit.utils.ImageLoader;
import org.multibit.viewsystem.View;
import org.multibit.viewsystem.ViewSystem;
import org.multibit.viewsystem.swing.action.CreateWalletSubmitAction;
import org.multibit.viewsystem.swing.action.DeleteWalletAction;
import org.multibit.viewsystem.swing.action.ExitAction;
import org.multibit.viewsystem.swing.action.HelpContextAction;
import org.multibit.viewsystem.swing.action.MnemonicUtil;
import org.multibit.viewsystem.swing.action.MultiBitAction;
import org.multibit.viewsystem.swing.action.MultiBitWalletBusyAction;
import org.multibit.viewsystem.swing.action.OpenWalletAction;
import org.multibit.viewsystem.swing.view.HelpContentsPanel;
import org.multibit.viewsystem.swing.view.ViewFactory;
import org.multibit.viewsystem.swing.view.components.BlinkLabel;
import org.multibit.viewsystem.swing.view.components.FontSizer;
import org.multibit.viewsystem.swing.view.components.HelpButton;
import org.multibit.viewsystem.swing.view.components.MultiBitTitledPanel;
import org.multibit.viewsystem.swing.view.ticker.TickerTablePanel;
import org.multibit.viewsystem.swing.view.walletlist.SingleWalletPanel;
import org.multibit.viewsystem.swing.view.walletlist.WalletListPanel;
import org.simplericity.macify.eawt.ApplicationEvent;
import org.simplericity.macify.eawt.ApplicationListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.bitcoin.core.EncryptionType;
import com.google.bitcoin.core.Transaction;
import com.google.bitcoin.core.Wallet;
/*
* JFrame displaying Swing version of MultiBit
*/
public class MultiBitFrame extends JFrame implements ViewSystem, ApplicationListener, WalletBusyListener {
private static final Logger log = LoggerFactory.getLogger(MultiBitFrame.class);
private static final double PROPORTION_OF_VERTICAL_SCREEN_TO_FILL = 0.75D;
private static final double PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL = 0.80D;
public static final String EXAMPLE_LONG_FIELD_TEXT = "1JiM1UyTGqpLqgayxTPbWbcdVeoepmY6pK++++";
public static final int WIDTH_OF_LONG_FIELDS = 300;
public static final int WIDTH_OF_AMOUNT_FIELD = 150;
public static final int WALLET_WIDTH_DELTA = 30;
private static final int SCROLL_BAR_DELTA = 20;
public static final int HEIGHT_OF_HEADER = 64;
private StatusBar statusBar;
private StatusEnum online = StatusEnum.CONNECTING;
public static final String SEPARATOR = " - ";
private static final long serialVersionUID = 7621813615342923041L;
private MultiBitController controller;
private MultiBitModel model;
private Localiser localiser;
private String helpContext;
public String getHelpContext() {
return helpContext;
}
public void setHelpContext(String helpContext) {
this.helpContext = helpContext;
}
private BlinkLabel estimatedBalanceTextLabel;
public BlinkLabel getEstimatedBalanceTextLabel() {
return estimatedBalanceTextLabel;
}
private HelpButton availableBalanceTextButton;
/**
* list of wallets shown in left hand column
*/
private WalletListPanel walletsView;
private MultiBitFrame thisFrame;
private JSplitPane splitPane;
private static final int TOOLTIP_DISMISSAL_DELAY = 12000; // millisecs
/**
* Provide the Application reference during construction
*/
private final GenericApplication application;
/**
* the tabbed pane containing the views
*
*/
private MultiBitTabbedPane viewTabbedPane;
public Logger logger = LoggerFactory.getLogger(MultiBitFrame.class.getName());
private ViewFactory viewFactory;
private Timer fileChangeTimer;
private Timer tickerTimer;
private JPanel headerPanel;
private TickerTablePanel tickerTablePanel;
private MultiBitWalletBusyAction addPasswordAction;
private MultiBitWalletBusyAction changePasswordAction;
private MultiBitWalletBusyAction removePasswordAction;
private MultiBitWalletBusyAction showImportPrivateKeysAction;
private MultiBitWalletBusyAction showExportPrivateKeysAction;
@SuppressWarnings("deprecation")
public MultiBitFrame(MultiBitController controller, GenericApplication application) {
this.controller = controller;
this.model = controller.getModel();
this.localiser = controller.getLocaliser();
this.thisFrame = this;
this.application = application;
FontSizer.INSTANCE.initialise(controller);
UIManager.put("ToolTip.font", FontSizer.INSTANCE.getAdjustedDefaultFont());
setCursor(Cursor.WAIT_CURSOR);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
String titleText = localiser.getString("multiBitFrame.title");
if (controller.getModel().getActiveWallet() != null) {
titleText = titleText + SEPARATOR + controller.getModel().getActivePerWalletModelData().getWalletDescription()
+ SEPARATOR + controller.getModel().getActivePerWalletModelData().getWalletFilename();
}
setTitle(titleText);
ToolTipManager.sharedInstance().setDismissDelay(TOOLTIP_DISMISSAL_DELAY);
final MultiBitController finalController = controller;
// TODO Examine how this fits in with the controller onQuit() event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
org.multibit.viewsystem.swing.action.ExitAction exitAction = new org.multibit.viewsystem.swing.action.ExitAction(
finalController, thisFrame);
exitAction.actionPerformed(null);
}
});
getContentPane().setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
sizeAndCenter();
viewFactory = new ViewFactory(controller, this);
initUI();
controller.registerWalletBusyListener(this);
applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
recreateAllViews(false);
// Initialise status bar.
statusBar.initialise();
// Initialise the file change timer.
fileChangeTimer = new Timer();
fileChangeTimer.schedule(new FileChangeTimerTask(controller, this), 0, FileChangeTimerTask.DEFAULT_REPEAT_RATE);
// Initialise the ticker.
tickerTimer = new Timer();
tickerTimer.schedule(new TickerTimerTask(controller, this), 0, TickerTimerTask.DEFAULT_REPEAT_RATE);
estimatedBalanceTextLabel.setText(controller.getLocaliser().bitcoinValueToString4(model.getActiveWalletEstimatedBalance(),
true, false));
availableBalanceTextButton.setText(controller.getLocaliser().getString(
"multiBitFrame.availableToSpend",
new Object[] { controller.getLocaliser()
.bitcoinValueToString4(model.getActiveWalletAvailableBalance(), true, false) }));
estimatedBalanceTextLabel.setFocusable(false);
availableBalanceTextButton.setFocusable(false);
walletsView.displayView();
int dividerPosition = SingleWalletPanel.calculateNormalWidth((JComponent) (walletsView)) + WALLET_WIDTH_DELTA;
if (((WalletListPanel) walletsView).getScrollPane().isVisible()) {
dividerPosition += SCROLL_BAR_DELTA;
}
splitPane.setDividerLocation(dividerPosition);
pack();
setVisible(true);
}
public GenericApplication getApplication() {
return application;
}
private void sizeAndCenter() {
// Get the screen size as a java dimension.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = (int) (screenSize.height * PROPORTION_OF_VERTICAL_SCREEN_TO_FILL);
int width = (int) (screenSize.width * PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL);
// Set the jframe height and width.
setPreferredSize(new Dimension(width, height));
double startVerticalPositionRatio = (1 - PROPORTION_OF_VERTICAL_SCREEN_TO_FILL) / 2;
double startHorizontalPositionRatio = (1 - PROPORTION_OF_HORIZONTAL_SCREEN_TO_FILL) / 2;
setLocation((int) (width * startHorizontalPositionRatio), (int) (height * startVerticalPositionRatio));
}
private void initUI() {
Container contentPane = getContentPane();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
GridBagConstraints constraints2 = new GridBagConstraints();
// Set the application icon.
ImageIcon imageIcon = ImageLoader.createImageIcon(ImageLoader.MULTIBIT_ICON_FILE);
if (imageIcon != null) {
setIconImage(imageIcon.getImage());
}
headerPanel = new JPanel();
headerPanel.setOpaque(false);
headerPanel.setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
headerPanel.setLayout(new GridBagLayout());
JPanel balancePanel = createBalancePanel();
constraints2.fill = GridBagConstraints.BOTH;
constraints2.gridx = 0;
constraints2.gridy = 0;
constraints2.gridwidth = 1;
constraints2.gridheight = 1;
constraints2.weightx = 1.0;
constraints2.weighty = 1.0;
constraints2.anchor = GridBagConstraints.LINE_START;
headerPanel.add(balancePanel, constraints2);
addMenuBar(constraints, contentPane);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 2;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.anchor = GridBagConstraints.LINE_START;
contentPane.add(headerPanel, constraints);
// Create the wallet list panel.
walletsView = new WalletListPanel(controller, this);
// Create the tabbedpane that holds the views.
viewTabbedPane = new MultiBitTabbedPane(controller);
viewTabbedPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
// Add the send bitcoin tab.
JPanel sendBitcoinOutlinePanel = new JPanel(new BorderLayout());
View sendBitcoinView = viewFactory.getView(View.SEND_BITCOIN_VIEW);
sendBitcoinOutlinePanel.add((JPanel) sendBitcoinView, BorderLayout.CENTER);
viewTabbedPane.addTab(sendBitcoinView.getViewTitle(), sendBitcoinView.getViewIcon(), sendBitcoinView.getViewTooltip(),
sendBitcoinOutlinePanel);
// Add the receive bitcoin tab.
JPanel receiveBitcoinOutlinePanel = new JPanel(new BorderLayout());
View receiveBitcoinView = viewFactory.getView(View.RECEIVE_BITCOIN_VIEW);
receiveBitcoinOutlinePanel.add((JPanel) receiveBitcoinView, BorderLayout.CENTER);
viewTabbedPane.addTab(receiveBitcoinView.getViewTitle(), receiveBitcoinView.getViewIcon(),
receiveBitcoinView.getViewTooltip(), receiveBitcoinOutlinePanel);
// Add the transactions tab.
JPanel transactionsOutlinePanel = new JPanel(new BorderLayout());
View transactionsView = viewFactory.getView(View.TRANSACTIONS_VIEW);
transactionsOutlinePanel.add((JPanel) transactionsView, BorderLayout.CENTER);
viewTabbedPane.addTab(transactionsView.getViewTitle(), transactionsView.getViewIcon(), transactionsView.getViewTooltip(),
transactionsOutlinePanel);
viewTabbedPane.addChangeListener();
// Create a split pane with the two scroll panes in it.
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, (JPanel) walletsView, viewTabbedPane);
splitPane.setOneTouchExpandable(false);
splitPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, SystemColor.windowBorder));
splitPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1000.0;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
contentPane.add(splitPane, constraints);
int dividerPosition = SingleWalletPanel.calculateNormalWidth((JComponent) (walletsView)) + WALLET_WIDTH_DELTA;
if (((WalletListPanel) walletsView).getScrollPane().isVisible()) {
dividerPosition += ((WalletListPanel) walletsView).getScrollPane().getWidth();
}
splitPane.setDividerLocation(dividerPosition);
statusBar = new StatusBar(controller, this);
statusBar.updateOnlineStatusText(online);
MessageManager.INSTANCE.addMessageListener(statusBar);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.weightx = 1;
constraints.weighty = 0.1;
constraints.gridwidth = 2;
contentPane.add(statusBar, constraints);
}
private JPanel createBalancePanel() {
JPanel headerPanel = new JPanel();
headerPanel.setMinimumSize(new Dimension(700, HEIGHT_OF_HEADER));
headerPanel.setPreferredSize(new Dimension(700, HEIGHT_OF_HEADER));
headerPanel.setOpaque(false);
headerPanel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
JLabel filler1 = new JLabel();
filler1.setMinimumSize(new Dimension(20, 20));
filler1.setMaximumSize(new Dimension(20, 20));
filler1.setPreferredSize(new Dimension(20, 20));
filler1.setOpaque(false);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 0.01;
constraints.gridwidth = 1;
constraints.gridheight = 2;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(filler1, constraints);
JLabel walletIconLabel = new JLabel();
if (ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()).isLeftToRight()) {
walletIconLabel.setIcon(ImageLoader.createImageIcon(ImageLoader.WALLET_ICON_FILE));
} else {
walletIconLabel.setIcon(ImageLoader.createImageIcon(ImageLoader.RTL_WALLET_ICON_FILE));
}
int walletIconWidth = 60;
int walletIconHeight = HEIGHT_OF_HEADER - 10;
walletIconLabel.setOpaque(false);
walletIconLabel.setMinimumSize(new Dimension(walletIconWidth, walletIconHeight));
walletIconLabel.setMaximumSize(new Dimension(walletIconWidth, walletIconHeight));
walletIconLabel.setPreferredSize(new Dimension(walletIconWidth, walletIconHeight));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 0.01;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(walletIconLabel, constraints);
constraints.gridx = 2;
constraints.gridy = 0;
constraints.weightx = 0.01;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(MultiBitTitledPanel.createStent(10), constraints);
estimatedBalanceTextLabel = new BlinkLabel(controller, true);
estimatedBalanceTextLabel.setHorizontalAlignment(JTextField.LEFT);
estimatedBalanceTextLabel.setToolTipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip"));
constraints.gridx = 3;
constraints.gridy = 0;
constraints.weightx = 0.6;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(estimatedBalanceTextLabel, constraints);
Action availableBalanceHelpAction = new HelpContextAction(controller, null, "multiBitFrame.helpMenuText",
"multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText", HelpContentsPanel.HELP_AVAILABLE_TO_SPEND_URL);
availableBalanceTextButton = new HelpButton(availableBalanceHelpAction, controller);
String tooltipText = HelpContentsPanel.createMultilineTooltipText(new String[] {
controller.getLocaliser().getString("multiBitFrame.availableToSpend.tooltip"), "\n",
controller.getLocaliser().getString("multiBitFrame.helpMenuTooltip") });
availableBalanceTextButton.setToolTipText(tooltipText);
// Initially invisible.
availableBalanceTextButton.setVisible(false);
availableBalanceTextButton.setEnabled(false);
constraints.gridx = 4;
constraints.gridy = 0;
constraints.weightx = 3.0;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(availableBalanceTextButton, constraints);
JPanel filler3 = new JPanel();
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 5;
constraints.gridy = 0;
constraints.weightx = 1000;
constraints.anchor = GridBagConstraints.LINE_START;
headerPanel.add(filler3, constraints);
// Add ticker panel.
tickerTablePanel = new TickerTablePanel(this, controller);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 6;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.CENTER;
headerPanel.add(tickerTablePanel, constraints);
// Add a little stent to keep it off the right hand edge.
int stent = 6; // A reasonable default.
Insets tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets");
if (tabAreaInsets != null) {
stent = tabAreaInsets.right;
}
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 7;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.anchor = GridBagConstraints.BASELINE_TRAILING;
headerPanel.add(MultiBitTitledPanel.createStent(stent), constraints);
return headerPanel;
}
/**
* @param constraints
* @param contentPane
*/
private void addMenuBar(GridBagConstraints constraints, Container contentPane) {
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale());
// Create the toolBar.
JPanel toolBarPanel = new JPanel();
toolBarPanel.setOpaque(false);
MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser());
// Build the File menu.
JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText"));
fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
fileMenu.setComponentOrientation(componentOrientation);
fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic"));
menuBar.add(fileMenu);
// Build the Trade menu.
JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText"));
tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
tradeMenu.setComponentOrientation(componentOrientation);
tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic"));
menuBar.add(tradeMenu);
// Build the View menu.
JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText"));
viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
viewMenu.setComponentOrientation(componentOrientation);
viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic"));
menuBar.add(viewMenu);
// Build the Tools menu.
JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText"));
toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
toolsMenu.setComponentOrientation(componentOrientation);
toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic"));
menuBar.add(toolsMenu);
// Build the Help menu.
JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText"));
helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
helpMenu.setComponentOrientation(componentOrientation);
helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic"));
menuBar.add(helpMenu);
// Create new wallet action.
CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(controller,
ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this);
JMenuItem menuItem = new JMenuItem(createNewWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Open wallet action.
OpenWalletAction openWalletAction = new OpenWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(openWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
DeleteWalletAction deleteWalletAction = new DeleteWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(deleteWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
fileMenu.addSeparator();
// Add password action.
addPasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text",
"addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW);
menuItem = new JMenuItem(addPasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Change password action.
changePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text",
"changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW);
menuItem = new JMenuItem(changePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Remove password action.
removePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text",
"removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW);
menuItem = new JMenuItem(removePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Exit action.
if (application != null && !application.isMac()) {
// Non Macs have an Exit Menu item.
fileMenu.addSeparator();
menuItem = new JMenuItem(new ExitAction(controller, this));
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
}
// Show welcome action.
MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text",
"welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW);
menuItem = new JMenuItem(showWelcomeAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
// Show help contents action.
MultiBitAction showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE,
"showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic",
View.HELP_CONTENTS_VIEW);
menuItem = new JMenuItem(showHelpContentsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
if (application != null && !application.isMac()) {
// Non Macs have a Help About menu item.
MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE,
"helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW);
menuItem = new JMenuItem(helpAboutAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
}
// ViewTransactions action.
MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE,
"showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic",
View.TRANSACTIONS_VIEW);
menuItem = new JMenuItem(showTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Show messages action.
MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text",
- "messagesPanel.title", "messagesPanel.mnemonic", View.MESSAGES_VIEW);
+ "messagesPanel.tooltip", "messagesPanel.mnemonic", View.MESSAGES_VIEW);
menuItem = new JMenuItem(showMessagesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Send bitcoin action.
MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE,
"sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW);
menuItem = new JMenuItem(sendBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE,
"receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic",
View.RECEIVE_BITCOIN_VIEW);
menuItem = new JMenuItem(receiveBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
// Show preferences.
if (application != null && !application.isMac()) {
// Non Macs have a Preferences menu item.
MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE,
"showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic",
View.PREFERENCES_VIEW);
menuItem = new JMenuItem(showPreferencesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
}
viewMenu.addSeparator();
// show ticker
String viewTicker = controller.getModel().getUserPreference(MultiBitModel.TICKER_SHOW);
boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker);
String tickerKey;
if (isTickerVisible) {
tickerKey = "multiBitFrame.ticker.hide.text";
} else {
tickerKey = "multiBitFrame.ticker.show.text";
}
final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey));
showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
showTicker.setComponentOrientation(componentOrientation);
showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE));
if (tickerTablePanel != null) {
tickerTablePanel.setVisible(isTickerVisible);
}
showTicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (tickerTablePanel != null) {
if (tickerTablePanel.isVisible()) {
tickerTablePanel.setVisible(false);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.FALSE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text"));
tickerTimer.cancel();
} else {
tickerTablePanel.setVisible(true);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.TRUE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text"));
// start ticker timer
tickerTimer = new Timer();
tickerTimer.schedule(new TickerTimerTask(controller, thisFrame), 0, TickerTimerTask.DEFAULT_REPEAT_RATE);
}
}
}
});
viewMenu.add(showTicker);
// Import private keys.
showImportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE,
"showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic",
View.SHOW_IMPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showImportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
// Export private keys.
showExportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE,
"showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic",
View.SHOW_EXPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showExportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
toolsMenu.addSeparator();
MultiBitAction resetTransactionsAction = new MultiBitAction(controller, ImageLoader.RESET_TRANSACTIONS_ICON_FILE,
"resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic",
View.RESET_TRANSACTIONS_VIEW);
menuItem = new JMenuItem(resetTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
setJMenuBar(menuBar);
return;
}
/**
* Recreate all views.
*/
public void recreateAllViews(boolean initUI) {
// Close down current view.
if (controller.getCurrentView() != 0) {
navigateAwayFromView(controller.getCurrentView());
}
if (initUI) {
this.localiser = controller.getLocaliser();
Container contentPane = getContentPane();
contentPane.removeAll();
initUI();
applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
}
statusBar.refreshOnlineStatusText();
updateHeader();
viewFactory = new ViewFactory(controller, this);
// Tell the wallets list to display.
if (walletsView != null) {
walletsView.initUI();
walletsView.displayView();
}
// Tell all the tabs in the tabbedPane to update.
if (viewTabbedPane != null) {
for (int i = 0; i < viewTabbedPane.getTabCount(); i++) {
JPanel tabComponent = (JPanel) viewTabbedPane.getComponentAt(i);
Component[] components = tabComponent.getComponents();
if (components != null && components.length > 0 && components[0] instanceof View) {
View loopView = ((View) components[0]);
loopView.displayView();
if (loopView.getViewId() == controller.getCurrentView()) {
viewTabbedPane.setSelectedIndex(i);
}
}
}
}
invalidate();
validate();
repaint();
}
/**
* Display next view on Swing event dispatch thread.
*/
public void displayView(int viewToDisplay) {
// Open wallet view obselete - show transactions
if (View.OPEN_WALLET_VIEW == viewToDisplay) {
viewToDisplay = View.TRANSACTIONS_VIEW;
}
// Create Bulk addreses obselete - show transactions
if (View.CREATE_BULK_ADDRESSES_VIEW == viewToDisplay) {
viewToDisplay = View.TRANSACTIONS_VIEW;
}
// Show wallets view always on display.
if (View.YOUR_WALLETS_VIEW == viewToDisplay) {
walletsView.displayView();
return;
}
controller.setCurrentView(viewToDisplay);
final View nextViewFinal = viewFactory.getView(viewToDisplay);
if (nextViewFinal == null) {
log.debug("Cannot display view " + viewToDisplay);
return;
}
final MultiBitFrame thisFrame = this;
SwingUtilities.invokeLater(new Runnable() {
@SuppressWarnings("deprecation")
public void run() {
String viewTitle = nextViewFinal.getViewTitle();
boolean foundTab = false;
if (viewTabbedPane.getTabCount() > 0) {
for (int i = 0; i < viewTabbedPane.getTabCount(); i++) {
JPanel tabComponent = (JPanel) viewTabbedPane.getComponentAt(i);
if (tabComponent != null) {
Component[] childComponents = tabComponent.getComponents();
String tabTitle = null;
if (childComponents != null && childComponents.length > 0 && childComponents[0] instanceof View) {
tabTitle = ((View) childComponents[0]).getViewTitle();
}
if (viewTitle != null && viewTitle.equals(tabTitle)) {
foundTab = true;
((JPanel) viewTabbedPane.getComponentAt(i)).removeAll();
((JPanel) viewTabbedPane.getComponentAt(i)).add((JPanel) nextViewFinal);
viewTabbedPane.setSelectedIndex(i);
}
}
}
}
if (!foundTab && nextViewFinal instanceof JPanel) {
JPanel tabOutlinePanel = new JPanel(new BorderLayout());
tabOutlinePanel.add((JPanel) nextViewFinal, BorderLayout.CENTER);
viewTabbedPane.addTab(nextViewFinal.getViewTitle(), nextViewFinal.getViewIcon(),
nextViewFinal.getViewTooltip(), tabOutlinePanel, true);
viewTabbedPane.setSelectedComponent(tabOutlinePanel);
}
nextViewFinal.displayView();
if (nextViewFinal instanceof JPanel) {
((JPanel) nextViewFinal).invalidate();
((JPanel) nextViewFinal).validate();
((JPanel) nextViewFinal).repaint();
}
thisFrame.setCursor(Cursor.DEFAULT_CURSOR);
}
});
}
/**
* Navigate away from view - this may be on another thread hence the
* SwingUtilities.invokeLater.
*/
public void navigateAwayFromView(int viewToNavigateAwayFrom) {
if (View.YOUR_WALLETS_VIEW == viewToNavigateAwayFrom) {
// Do nothing
return;
}
final View viewToNavigateAwayFromFinal = viewFactory.getView(viewToNavigateAwayFrom);
if (viewToNavigateAwayFromFinal != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
viewToNavigateAwayFromFinal.navigateAwayFromView();
}
});
}
}
@Override
public void setOnlineStatus(StatusEnum statusEnum) {
online = statusEnum;
if (statusBar != null) {
statusBar.updateOnlineStatusText(statusEnum);
}
}
@Override
public void walletBusyChange(boolean newWalletIsBusy) {
updateMenuItemsOnWalletChange();
}
public void updateMenuItemsOnWalletChange() {
showImportPrivateKeysAction.setEnabled(!controller.getModel().getActivePerWalletModelData().isBusy());
showExportPrivateKeysAction.setEnabled(!controller.getModel().getActivePerWalletModelData().isBusy());
if (controller.getModel().getActiveWallet() == null) {
// Cannot do anything password related.
addPasswordAction.setEnabled(false);
changePasswordAction.setEnabled(false);
removePasswordAction.setEnabled(false);
} else {
if (controller.getModel().getActivePerWalletModelData().isBusy()) {
addPasswordAction.setEnabled(false);
changePasswordAction.setEnabled(false);
removePasswordAction.setEnabled(false);
} else {
if (controller.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) {
addPasswordAction.setEnabled(false);
changePasswordAction.setEnabled(true);
removePasswordAction.setEnabled(true);
} else {
if (controller.getModel().getActiveWalletWalletInfo().getWalletMajorVersion() == WalletMajorVersion.SERIALIZED) {
addPasswordAction.setEnabled(false);
} else {
addPasswordAction.setEnabled(true);
}
changePasswordAction.setEnabled(false);
removePasswordAction.setEnabled(false);
}
}
}
}
@Override
/**
* Update due to a block being downloaded
* This typically comes in from a Peer so is 'SwingUtilitied' to get the request on the Swing event thread
*/
public void blockDownloaded() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Update transaction screen in case status bars have changed.
if (View.TRANSACTIONS_VIEW == controller.getCurrentView()) {
thisFrame.fireDataChanged();
}
}
});
}
@Override
public void onCoinsReceived(Wallet wallet, Transaction transaction, BigInteger prevBalance, BigInteger newBalance) {
}
@Override
public void onCoinsSent(Wallet wallet, Transaction transaction, BigInteger prevBalance, BigInteger newBalance) {
}
/**
* One of the wallets has been reorganised due to a block chain reorganise.
*/
@Override
public void onReorganize(Wallet wallet) {
log.info("Wallet has been reorganised.");
recreateAllViews(false);
}
public void onTransactionConfidenceChanged(Wallet wallet, Transaction transaction) {
//log.debug("Transaction confidence changed for tx " + transaction.toString());
}
public void fireFilesHaveBeenChangedByAnotherProcess(PerWalletModelData perWalletModelData) {
if (controller.getModel().getActiveWalletFilename() != null
&& controller.getModel().getActiveWalletFilename().equals(perWalletModelData.getWalletFilename())) {
Message message = new Message(controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.1") + " "
+ controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.2"), true);
MessageManager.INSTANCE.addMessage(message);
}
fireDataChanged();
}
/**
* Update the UI after the model data has changed.
*/
public void fireDataChanged() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Update the password related menu items.
updateMenuItemsOnWalletChange();
// Update the header.
updateHeader();
// Tell the wallets list to display.
if (walletsView != null) {
walletsView.displayView();
}
// Tell the current view to update itself.
View currentViewView = viewFactory.getView(controller.getCurrentView());
if (currentViewView != null) {
currentViewView.displayView();
}
thisFrame.invalidate();
thisFrame.validate();
thisFrame.repaint();
}
});
}
/**
* Update the Ticker Panel after the exchange data has changed.
*/
public void fireExchangeDataChanged() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tickerTablePanel.update();
}
});
}
private void updateHeader() {
if (controller.getModel().getActivePerWalletModelData() != null
&& controller.getModel().getActivePerWalletModelData().isFilesHaveBeenChangedByAnotherProcess()) {
// Files have been changed by another process - blank totals
// and put 'Updates stopped' message.
estimatedBalanceTextLabel.setText(controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.text"));
setUpdatesStoppedTooltip(estimatedBalanceTextLabel);
availableBalanceTextButton.setText("");
} else {
estimatedBalanceTextLabel.setText(controller.getLocaliser().bitcoinValueToString4(
controller.getModel().getActiveWalletEstimatedBalance(), true, false));
estimatedBalanceTextLabel.setToolTipText(controller.getLocaliser().getString("multiBitFrame.balanceLabel.tooltip"));
if (model.getActiveWalletAvailableBalance() != null
&& model.getActiveWalletAvailableBalance().equals(controller.getModel().getActiveWalletEstimatedBalance())) {
availableBalanceTextButton.setText("");
availableBalanceTextButton.setEnabled(false);
availableBalanceTextButton.setVisible(false);
} else {
availableBalanceTextButton.setText(controller.getLocaliser().getString(
"multiBitFrame.availableToSpend",
new Object[] { controller.getLocaliser().bitcoinValueToString4(model.getActiveWalletAvailableBalance(),
true, false) }));
availableBalanceTextButton.setEnabled(true);
availableBalanceTextButton.setVisible(true);
}
String titleText = localiser.getString("multiBitFrame.title");
if (controller.getModel().getActiveWallet() != null) {
titleText = titleText + SEPARATOR + controller.getModel().getActivePerWalletModelData().getWalletDescription()
+ SEPARATOR + controller.getModel().getActivePerWalletModelData().getWalletFilename();
}
setTitle(titleText);
}
}
// Macify application methods.
@Override
@Deprecated
public void handleAbout(ApplicationEvent event) {
controller.displayView(View.HELP_ABOUT_VIEW);
event.setHandled(true);
}
@Override
@Deprecated
public void handleOpenApplication(ApplicationEvent event) {
// Ok, we know our application started.
// Not much to do about that..
}
@Override
@Deprecated
public void handleOpenFile(ApplicationEvent event) {
// TODO i18n required.
JOptionPane.showMessageDialog(this, "Sorry, opening of files with double click is not yet implemented. Wallet was "
+ event.getFilename());
}
@Override
@Deprecated
public void handlePreferences(ApplicationEvent event) {
controller.displayView(View.PREFERENCES_VIEW);
}
@Override
@Deprecated
public void handlePrintFile(ApplicationEvent event) {
// TODO i18n required.
JOptionPane.showMessageDialog(this, "Sorry, printing not implemented");
}
@Override
@Deprecated
public void handleQuit(ApplicationEvent event) {
ExitAction exitAction = new ExitAction(controller, this);
exitAction.actionPerformed(null);
}
@Override
public void handleReOpenApplication(ApplicationEvent event) {
setVisible(true);
}
public void setUpdatesStoppedTooltip(JComponent component) {
// Multiline tool tip text.
String toolTipText = "<html><font face=\"sansserif\">";
toolTipText = toolTipText + controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.1") + "<br>";
toolTipText = toolTipText + controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.tooltip.2") + "<br>";
toolTipText = toolTipText + "</font></html>";
component.setToolTipText(toolTipText);
}
public void bringToFront() {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
toFront();
repaint();
}
});
}
public WalletListPanel getWalletsView() {
return walletsView;
}
public void onDeadTransaction(Wallet wallet, Transaction deadTx, Transaction replacementTx) {
}
public JPanel getHeaderPanel() {
return headerPanel;
}
public TickerTablePanel getTickerTablePanel() {
return tickerTablePanel;
}
}
| true | true | private void addMenuBar(GridBagConstraints constraints, Container contentPane) {
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale());
// Create the toolBar.
JPanel toolBarPanel = new JPanel();
toolBarPanel.setOpaque(false);
MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser());
// Build the File menu.
JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText"));
fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
fileMenu.setComponentOrientation(componentOrientation);
fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic"));
menuBar.add(fileMenu);
// Build the Trade menu.
JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText"));
tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
tradeMenu.setComponentOrientation(componentOrientation);
tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic"));
menuBar.add(tradeMenu);
// Build the View menu.
JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText"));
viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
viewMenu.setComponentOrientation(componentOrientation);
viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic"));
menuBar.add(viewMenu);
// Build the Tools menu.
JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText"));
toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
toolsMenu.setComponentOrientation(componentOrientation);
toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic"));
menuBar.add(toolsMenu);
// Build the Help menu.
JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText"));
helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
helpMenu.setComponentOrientation(componentOrientation);
helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic"));
menuBar.add(helpMenu);
// Create new wallet action.
CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(controller,
ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this);
JMenuItem menuItem = new JMenuItem(createNewWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Open wallet action.
OpenWalletAction openWalletAction = new OpenWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(openWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
DeleteWalletAction deleteWalletAction = new DeleteWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(deleteWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
fileMenu.addSeparator();
// Add password action.
addPasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text",
"addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW);
menuItem = new JMenuItem(addPasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Change password action.
changePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text",
"changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW);
menuItem = new JMenuItem(changePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Remove password action.
removePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text",
"removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW);
menuItem = new JMenuItem(removePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Exit action.
if (application != null && !application.isMac()) {
// Non Macs have an Exit Menu item.
fileMenu.addSeparator();
menuItem = new JMenuItem(new ExitAction(controller, this));
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
}
// Show welcome action.
MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text",
"welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW);
menuItem = new JMenuItem(showWelcomeAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
// Show help contents action.
MultiBitAction showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE,
"showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic",
View.HELP_CONTENTS_VIEW);
menuItem = new JMenuItem(showHelpContentsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
if (application != null && !application.isMac()) {
// Non Macs have a Help About menu item.
MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE,
"helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW);
menuItem = new JMenuItem(helpAboutAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
}
// ViewTransactions action.
MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE,
"showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic",
View.TRANSACTIONS_VIEW);
menuItem = new JMenuItem(showTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Show messages action.
MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text",
"messagesPanel.title", "messagesPanel.mnemonic", View.MESSAGES_VIEW);
menuItem = new JMenuItem(showMessagesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Send bitcoin action.
MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE,
"sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW);
menuItem = new JMenuItem(sendBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE,
"receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic",
View.RECEIVE_BITCOIN_VIEW);
menuItem = new JMenuItem(receiveBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
// Show preferences.
if (application != null && !application.isMac()) {
// Non Macs have a Preferences menu item.
MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE,
"showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic",
View.PREFERENCES_VIEW);
menuItem = new JMenuItem(showPreferencesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
}
viewMenu.addSeparator();
// show ticker
String viewTicker = controller.getModel().getUserPreference(MultiBitModel.TICKER_SHOW);
boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker);
String tickerKey;
if (isTickerVisible) {
tickerKey = "multiBitFrame.ticker.hide.text";
} else {
tickerKey = "multiBitFrame.ticker.show.text";
}
final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey));
showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
showTicker.setComponentOrientation(componentOrientation);
showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE));
if (tickerTablePanel != null) {
tickerTablePanel.setVisible(isTickerVisible);
}
showTicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (tickerTablePanel != null) {
if (tickerTablePanel.isVisible()) {
tickerTablePanel.setVisible(false);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.FALSE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text"));
tickerTimer.cancel();
} else {
tickerTablePanel.setVisible(true);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.TRUE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text"));
// start ticker timer
tickerTimer = new Timer();
tickerTimer.schedule(new TickerTimerTask(controller, thisFrame), 0, TickerTimerTask.DEFAULT_REPEAT_RATE);
}
}
}
});
viewMenu.add(showTicker);
// Import private keys.
showImportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE,
"showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic",
View.SHOW_IMPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showImportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
// Export private keys.
showExportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE,
"showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic",
View.SHOW_EXPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showExportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
toolsMenu.addSeparator();
MultiBitAction resetTransactionsAction = new MultiBitAction(controller, ImageLoader.RESET_TRANSACTIONS_ICON_FILE,
"resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic",
View.RESET_TRANSACTIONS_VIEW);
menuItem = new JMenuItem(resetTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
setJMenuBar(menuBar);
return;
}
| private void addMenuBar(GridBagConstraints constraints, Container contentPane) {
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(controller.getLocaliser().getLocale());
// Create the toolBar.
JPanel toolBarPanel = new JPanel();
toolBarPanel.setOpaque(false);
MnemonicUtil mnemonicUtil = new MnemonicUtil(controller.getLocaliser());
// Build the File menu.
JMenu fileMenu = new JMenu(localiser.getString("multiBitFrame.fileMenuText"));
fileMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
fileMenu.setComponentOrientation(componentOrientation);
fileMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.fileMenuMnemonic"));
menuBar.add(fileMenu);
// Build the Trade menu.
JMenu tradeMenu = new JMenu(localiser.getString("multiBitFrame.tradeMenuText"));
tradeMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
tradeMenu.setComponentOrientation(componentOrientation);
tradeMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.tradeMenuMnemonic"));
menuBar.add(tradeMenu);
// Build the View menu.
JMenu viewMenu = new JMenu(localiser.getString("multiBitFrame.viewMenuText"));
viewMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
viewMenu.setComponentOrientation(componentOrientation);
viewMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.viewMenuMnemonic"));
menuBar.add(viewMenu);
// Build the Tools menu.
JMenu toolsMenu = new JMenu(localiser.getString("multiBitFrame.toolsMenuText"));
toolsMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
toolsMenu.setComponentOrientation(componentOrientation);
toolsMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.toolsMenuMnemonic"));
menuBar.add(toolsMenu);
// Build the Help menu.
JMenu helpMenu = new JMenu(localiser.getString("multiBitFrame.helpMenuText"));
helpMenu.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
helpMenu.setComponentOrientation(componentOrientation);
helpMenu.setMnemonic(mnemonicUtil.getMnemonic("multiBitFrame.helpMenuMnemonic"));
menuBar.add(helpMenu);
// Create new wallet action.
CreateWalletSubmitAction createNewWalletAction = new CreateWalletSubmitAction(controller,
ImageLoader.createImageIcon(ImageLoader.CREATE_NEW_ICON_FILE), this);
JMenuItem menuItem = new JMenuItem(createNewWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Open wallet action.
OpenWalletAction openWalletAction = new OpenWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.OPEN_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(openWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
DeleteWalletAction deleteWalletAction = new DeleteWalletAction(controller,
ImageLoader.createImageIcon(ImageLoader.DELETE_WALLET_ICON_FILE), this);
menuItem = new JMenuItem(deleteWalletAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
fileMenu.addSeparator();
// Add password action.
addPasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.ADD_PASSWORD_ICON_FILE, "addPasswordAction.text",
"addPasswordAction.tooltip", "addPasswordAction.mnemonic", View.ADD_PASSWORD_VIEW);
menuItem = new JMenuItem(addPasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Change password action.
changePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.CHANGE_PASSWORD_ICON_FILE, "changePasswordAction.text",
"changePasswordAction.tooltip", "changePasswordAction.mnemonic", View.CHANGE_PASSWORD_VIEW);
menuItem = new JMenuItem(changePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Remove password action.
removePasswordAction = new MultiBitWalletBusyAction(controller, ImageLoader.REMOVE_PASSWORD_ICON_FILE, "removePasswordAction.text",
"removePasswordAction.tooltip", "removePasswordAction.mnemonic", View.REMOVE_PASSWORD_VIEW);
menuItem = new JMenuItem(removePasswordAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
// Exit action.
if (application != null && !application.isMac()) {
// Non Macs have an Exit Menu item.
fileMenu.addSeparator();
menuItem = new JMenuItem(new ExitAction(controller, this));
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
fileMenu.add(menuItem);
}
// Show welcome action.
MultiBitAction showWelcomeAction = new MultiBitAction(controller, ImageLoader.WELCOME_ICON_FILE, "welcomePanel.text",
"welcomePanel.title", "welcomePanel.mnemonic", View.WELCOME_VIEW);
menuItem = new JMenuItem(showWelcomeAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
// Show help contents action.
MultiBitAction showHelpContentsAction = new MultiBitAction(controller, ImageLoader.HELP_CONTENTS_ICON_FILE,
"showHelpContentsAction.text", "showHelpContentsAction.tooltip", "showHelpContentsAction.mnemonic",
View.HELP_CONTENTS_VIEW);
menuItem = new JMenuItem(showHelpContentsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
if (application != null && !application.isMac()) {
// Non Macs have a Help About menu item.
MultiBitAction helpAboutAction = new MultiBitAction(controller, ImageLoader.MULTIBIT_SMALL_ICON_FILE,
"helpAboutAction.text", "helpAboutAction.tooltip", "helpAboutAction.mnemonic", View.HELP_ABOUT_VIEW);
menuItem = new JMenuItem(helpAboutAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
helpMenu.add(menuItem);
}
// ViewTransactions action.
MultiBitAction showTransactionsAction = new MultiBitAction(controller, ImageLoader.TRANSACTIONS_ICON_FILE,
"showTransactionsAction.text", "showTransactionsAction.tooltip", "showTransactionsAction.mnemonic",
View.TRANSACTIONS_VIEW);
menuItem = new JMenuItem(showTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Show messages action.
MultiBitAction showMessagesAction = new MultiBitAction(controller, ImageLoader.MESSAGES_ICON_FILE, "messagesPanel.text",
"messagesPanel.tooltip", "messagesPanel.mnemonic", View.MESSAGES_VIEW);
menuItem = new JMenuItem(showMessagesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
// Send bitcoin action.
MultiBitAction sendBitcoinAction = new MultiBitAction(controller, ImageLoader.SEND_BITCOIN_ICON_FILE,
"sendBitcoinAction.text", "sendBitcoinAction.tooltip", "sendBitcoinAction.mnemonic", View.SEND_BITCOIN_VIEW);
menuItem = new JMenuItem(sendBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
MultiBitAction receiveBitcoinAction = new MultiBitAction(controller, ImageLoader.RECEIVE_BITCOIN_ICON_FILE,
"receiveBitcoinAction.text", "receiveBitcoinAction.tooltip", "receiveBitcoinAction.mnemonic",
View.RECEIVE_BITCOIN_VIEW);
menuItem = new JMenuItem(receiveBitcoinAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
tradeMenu.add(menuItem);
// Show preferences.
if (application != null && !application.isMac()) {
// Non Macs have a Preferences menu item.
MultiBitAction showPreferencesAction = new MultiBitAction(controller, ImageLoader.PREFERENCES_ICON_FILE,
"showPreferencesAction.text", "showPreferencesAction.tooltip", "showPreferencesAction.mnemonic",
View.PREFERENCES_VIEW);
menuItem = new JMenuItem(showPreferencesAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
viewMenu.add(menuItem);
}
viewMenu.addSeparator();
// show ticker
String viewTicker = controller.getModel().getUserPreference(MultiBitModel.TICKER_SHOW);
boolean isTickerVisible = !Boolean.FALSE.toString().equals(viewTicker);
String tickerKey;
if (isTickerVisible) {
tickerKey = "multiBitFrame.ticker.hide.text";
} else {
tickerKey = "multiBitFrame.ticker.show.text";
}
final JMenuItem showTicker = new JMenuItem(controller.getLocaliser().getString(tickerKey));
showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
showTicker.setComponentOrientation(componentOrientation);
showTicker.setIcon(ImageLoader.createImageIcon(ImageLoader.MONEY_ICON_FILE));
if (tickerTablePanel != null) {
tickerTablePanel.setVisible(isTickerVisible);
}
showTicker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (tickerTablePanel != null) {
if (tickerTablePanel.isVisible()) {
tickerTablePanel.setVisible(false);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.FALSE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.show.text"));
tickerTimer.cancel();
} else {
tickerTablePanel.setVisible(true);
controller.getModel().setUserPreference(MultiBitModel.TICKER_SHOW, Boolean.TRUE.toString());
showTicker.setText(controller.getLocaliser().getString("multiBitFrame.ticker.hide.text"));
// start ticker timer
tickerTimer = new Timer();
tickerTimer.schedule(new TickerTimerTask(controller, thisFrame), 0, TickerTimerTask.DEFAULT_REPEAT_RATE);
}
}
}
});
viewMenu.add(showTicker);
// Import private keys.
showImportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE,
"showImportPrivateKeysAction.text", "showImportPrivateKeysAction.tooltip", "showImportPrivateKeysAction.mnemonic",
View.SHOW_IMPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showImportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
// Export private keys.
showExportPrivateKeysAction = new MultiBitWalletBusyAction(controller, ImageLoader.EXPORT_PRIVATE_KEYS_ICON_FILE,
"showExportPrivateKeysAction.text", "showExportPrivateKeysAction.tooltip", "showExportPrivateKeysAction.mnemonic",
View.SHOW_EXPORT_PRIVATE_KEYS_VIEW);
menuItem = new JMenuItem(showExportPrivateKeysAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
toolsMenu.addSeparator();
MultiBitAction resetTransactionsAction = new MultiBitAction(controller, ImageLoader.RESET_TRANSACTIONS_ICON_FILE,
"resetTransactionsAction.text", "resetTransactionsAction.tooltip", "resetTransactionsAction.mnemonic",
View.RESET_TRANSACTIONS_VIEW);
menuItem = new JMenuItem(resetTransactionsAction);
menuItem.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont());
menuItem.setComponentOrientation(componentOrientation);
toolsMenu.add(menuItem);
setJMenuBar(menuBar);
return;
}
|
diff --git a/scoutmaster/src/main/java/au/org/scoutmaster/views/wizards/bulkSMS/ConfirmDetailsStep.java b/scoutmaster/src/main/java/au/org/scoutmaster/views/wizards/bulkSMS/ConfirmDetailsStep.java
index 8f58063..4d6d778 100644
--- a/scoutmaster/src/main/java/au/org/scoutmaster/views/wizards/bulkSMS/ConfirmDetailsStep.java
+++ b/scoutmaster/src/main/java/au/org/scoutmaster/views/wizards/bulkSMS/ConfirmDetailsStep.java
@@ -1,130 +1,131 @@
package au.org.scoutmaster.views.wizards.bulkSMS;
import java.util.ArrayList;
import org.vaadin.teemu.wizards.WizardStep;
import au.com.vaadinutils.crud.MultiColumnFormLayout;
import au.org.scoutmaster.application.SMSession;
import au.org.scoutmaster.domain.Contact;
import au.org.scoutmaster.domain.Phone;
import au.org.scoutmaster.domain.access.User;
import au.org.scoutmaster.util.SMNotification;
import au.org.scoutmaster.util.VelocityFormatException;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
public class ConfirmDetailsStep implements WizardStep
{
private TextField subject;
private TextArea message;
private TextField from;
private TextField provider;
private BulkSMSWizardView messagingWizardView;
private VerticalLayout layout;
private Label recipientCount;
private MessageDetailsStep details;
public ConfirmDetailsStep(BulkSMSWizardView messagingWizardView)
{
this.messagingWizardView = messagingWizardView;
details = messagingWizardView.getDetails();
layout = new VerticalLayout();
layout.addComponent(new Label(
"Please review the details before clicking next as messages will be sent immediately."));
layout.setWidth("100%");
recipientCount = new Label();
recipientCount.setContentMode(ContentMode.HTML);
layout.addComponent(recipientCount);
MultiColumnFormLayout<Object> formLayout = new MultiColumnFormLayout<>(1, null);
+ formLayout.setColumnFieldWidth(0, 500);
provider = formLayout.bindTextField("Provider", "provider");
provider.setReadOnly(true);
from = formLayout.bindTextField("From", "from");
from.setReadOnly(true);
subject = formLayout.bindTextField("Subject", "subject");
subject.setSizeFull();
subject.setReadOnly(true);
message = formLayout.bindTextAreaField("Message", "message", 4);
message.setReadOnly(true);
message.setWidth("100%");
layout.addComponent(formLayout);
layout.setMargin(true);
}
@Override
public String getCaption()
{
return "Confim Details";
}
@Override
public Component getContent()
{
recipientCount.setValue("<p><b>" + messagingWizardView.getRecipientStep().getRecipientCount()
+ " recipients have been selected to recieve the following Email.</b></p>");
ArrayList<Contact> recipients = messagingWizardView.getRecipientStep().getRecipients();
Contact sampleContact = recipients.get(0);
User user = (User) SMSession.INSTANCE.getLoggedInUser();
try
{
provider.setReadOnly(false);
provider.setValue(details.getProvider().getProviderName());
provider.setReadOnly(true);
from.setReadOnly(false);
from.setValue(details.getFrom());
from.setReadOnly(true);
subject.setReadOnly(false);
subject.setValue(details.getSubject());
subject.setReadOnly(true);
message.setReadOnly(false);
message.setValue(details.getMessage().expandBody(user, sampleContact).toString());
message.setReadOnly(true);
}
catch (VelocityFormatException e)
{
SMNotification.show(e, Type.ERROR_MESSAGE);
}
return layout;
}
@Override
public boolean onAdvance()
{
boolean advance = this.subject.getValue() != null && this.message.getValue() != null;
if (!advance)
Notification.show("Please enter a Subject and a Message then click Next");
return advance;
}
@Override
public boolean onBack()
{
return true;
}
public Message getMessage()
{
return new Message(subject.getValue(), message.getValue(), new Phone(from.getValue()));
}
}
| true | true | public ConfirmDetailsStep(BulkSMSWizardView messagingWizardView)
{
this.messagingWizardView = messagingWizardView;
details = messagingWizardView.getDetails();
layout = new VerticalLayout();
layout.addComponent(new Label(
"Please review the details before clicking next as messages will be sent immediately."));
layout.setWidth("100%");
recipientCount = new Label();
recipientCount.setContentMode(ContentMode.HTML);
layout.addComponent(recipientCount);
MultiColumnFormLayout<Object> formLayout = new MultiColumnFormLayout<>(1, null);
provider = formLayout.bindTextField("Provider", "provider");
provider.setReadOnly(true);
from = formLayout.bindTextField("From", "from");
from.setReadOnly(true);
subject = formLayout.bindTextField("Subject", "subject");
subject.setSizeFull();
subject.setReadOnly(true);
message = formLayout.bindTextAreaField("Message", "message", 4);
message.setReadOnly(true);
message.setWidth("100%");
layout.addComponent(formLayout);
layout.setMargin(true);
}
| public ConfirmDetailsStep(BulkSMSWizardView messagingWizardView)
{
this.messagingWizardView = messagingWizardView;
details = messagingWizardView.getDetails();
layout = new VerticalLayout();
layout.addComponent(new Label(
"Please review the details before clicking next as messages will be sent immediately."));
layout.setWidth("100%");
recipientCount = new Label();
recipientCount.setContentMode(ContentMode.HTML);
layout.addComponent(recipientCount);
MultiColumnFormLayout<Object> formLayout = new MultiColumnFormLayout<>(1, null);
formLayout.setColumnFieldWidth(0, 500);
provider = formLayout.bindTextField("Provider", "provider");
provider.setReadOnly(true);
from = formLayout.bindTextField("From", "from");
from.setReadOnly(true);
subject = formLayout.bindTextField("Subject", "subject");
subject.setSizeFull();
subject.setReadOnly(true);
message = formLayout.bindTextAreaField("Message", "message", 4);
message.setReadOnly(true);
message.setWidth("100%");
layout.addComponent(formLayout);
layout.setMargin(true);
}
|
diff --git a/android-liquibase/android-liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateTableGenerator.java b/android-liquibase/android-liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateTableGenerator.java
index 41ef60a..e850955 100644
--- a/android-liquibase/android-liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateTableGenerator.java
+++ b/android-liquibase/android-liquibase-core/src/main/java/liquibase/sqlgenerator/core/CreateTableGenerator.java
@@ -1,242 +1,242 @@
package liquibase.sqlgenerator.core;
import liquibase.database.Database;
import liquibase.database.core.*;
import liquibase.exception.ValidationErrors;
import liquibase.logging.LogFactory;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.AutoIncrementConstraint;
import liquibase.statement.ForeignKeyConstraint;
import liquibase.statement.UniqueConstraint;
import liquibase.statement.core.CreateTableStatement;
import liquibase.util.StringUtils;
import java.util.Iterator;
public class CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> {
public ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
ValidationErrors validationErrors = new ValidationErrors();
validationErrors.checkRequiredField("tableName", createTableStatement.getTableName());
validationErrors.checkRequiredField("columns", createTableStatement.getColumns());
return validationErrors;
}
public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" ");
buffer.append("(");
boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().size() == 1;
boolean isPrimaryKeyAutoIncrement = false;
Iterator<String> columnIterator = statement.getColumns().iterator();
while (columnIterator.hasNext()) {
String column = columnIterator.next();
buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column));
buffer.append(" ").append(statement.getColumnTypes().get(column));
AutoIncrementConstraint autoIncrementConstraint = null;
for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
autoIncrementConstraint = currentAutoIncrementConstraint;
break;
}
}
boolean isAutoIncrementColumn = autoIncrementConstraint != null;
boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().contains(column);
isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement
|| isPrimaryKeyColumn && isAutoIncrementColumn;
if ((database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyColumn &&
isAutoIncrementColumn) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
buffer.append(" PRIMARY KEY AUTOINCREMENT");
}
if (statement.getDefaultValue(column) != null) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column));
}
buffer.append(" DEFAULT ");
buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database));
}
- if (isAutoIncrementColumn) {
+ if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) {
// TODO: check if database supports auto increment on non primary key column
if (database.supportsAutoIncrement()) {
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
} else {
LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName())));
}
}
if (statement.getNotNullColumns().contains(column)) {
buffer.append(" NOT NULL");
} else {
if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) {
if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) {
//don't append null
} else {
buffer.append(" NULL");
}
}
}
if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) {
buffer.append(" PRIMARY KEY");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
// TODO informixdb
if (!( (database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyAutoIncrement) &&
!((database instanceof InformixDatabase) &&
isSinglePrimaryKeyColumn
)) {
// ...skip this code block for sqlite if a single column primary key
// with an autoincrement constraint exists.
// This constraint is added after the column type.
if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) {
if (!(database instanceof InformixDatabase)) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if (database instanceof OracleDatabase &&
statement.getPrimaryKeyConstraint().getTablespace() != null) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) {
referencesString = database.getDefaultSchemaName()+"."+referencesString;
}
buffer.append(" FOREIGN KEY (")
.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
.append(") REFERENCES ")
.append(referencesString);
if (fkConstraint.isDeleteCascade()) {
buffer.append(" ON DELETE CASCADE");
}
if ((database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
if (fkConstraint.isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (fkConstraint.isDeferrable()) {
buffer.append(" DEFERRABLE");
}
buffer.append(",");
}
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(",");
}
// if (constraints != null && constraints.getCheck() != null) {
// buffer.append(constraints.getCheck()).append(" ");
// }
// }
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
// if (StringUtils.trimToNull(tablespace) != null && database.supportsTablespaces()) {
// if (database instanceof MSSQLDatabase) {
// buffer.append(" ON ").append(tablespace);
// } else if (database instanceof DB2Database) {
// buffer.append(" IN ").append(tablespace);
// } else {
// buffer.append(" TABLESPACE ").append(tablespace);
// }
// }
if (statement.getTablespace() != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
sql += " ON " + statement.getTablespace();
} else if (database instanceof DB2Database || database instanceof InformixDatabase) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
return new Sql[] {
new UnparsedSql(sql)
};
}
private boolean constraintNameAfterUnique(Database database) {
return database instanceof InformixDatabase;
}
}
| true | true | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" ");
buffer.append("(");
boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().size() == 1;
boolean isPrimaryKeyAutoIncrement = false;
Iterator<String> columnIterator = statement.getColumns().iterator();
while (columnIterator.hasNext()) {
String column = columnIterator.next();
buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column));
buffer.append(" ").append(statement.getColumnTypes().get(column));
AutoIncrementConstraint autoIncrementConstraint = null;
for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
autoIncrementConstraint = currentAutoIncrementConstraint;
break;
}
}
boolean isAutoIncrementColumn = autoIncrementConstraint != null;
boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().contains(column);
isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement
|| isPrimaryKeyColumn && isAutoIncrementColumn;
if ((database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyColumn &&
isAutoIncrementColumn) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
buffer.append(" PRIMARY KEY AUTOINCREMENT");
}
if (statement.getDefaultValue(column) != null) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column));
}
buffer.append(" DEFAULT ");
buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database));
}
if (isAutoIncrementColumn) {
// TODO: check if database supports auto increment on non primary key column
if (database.supportsAutoIncrement()) {
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
} else {
LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName())));
}
}
if (statement.getNotNullColumns().contains(column)) {
buffer.append(" NOT NULL");
} else {
if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) {
if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) {
//don't append null
} else {
buffer.append(" NULL");
}
}
}
if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) {
buffer.append(" PRIMARY KEY");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
// TODO informixdb
if (!( (database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyAutoIncrement) &&
!((database instanceof InformixDatabase) &&
isSinglePrimaryKeyColumn
)) {
// ...skip this code block for sqlite if a single column primary key
// with an autoincrement constraint exists.
// This constraint is added after the column type.
if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) {
if (!(database instanceof InformixDatabase)) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if (database instanceof OracleDatabase &&
statement.getPrimaryKeyConstraint().getTablespace() != null) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) {
referencesString = database.getDefaultSchemaName()+"."+referencesString;
}
buffer.append(" FOREIGN KEY (")
.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
.append(") REFERENCES ")
.append(referencesString);
if (fkConstraint.isDeleteCascade()) {
buffer.append(" ON DELETE CASCADE");
}
if ((database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
if (fkConstraint.isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (fkConstraint.isDeferrable()) {
buffer.append(" DEFERRABLE");
}
buffer.append(",");
}
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(",");
}
// if (constraints != null && constraints.getCheck() != null) {
// buffer.append(constraints.getCheck()).append(" ");
// }
// }
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
// if (StringUtils.trimToNull(tablespace) != null && database.supportsTablespaces()) {
// if (database instanceof MSSQLDatabase) {
// buffer.append(" ON ").append(tablespace);
// } else if (database instanceof DB2Database) {
// buffer.append(" IN ").append(tablespace);
// } else {
// buffer.append(" TABLESPACE ").append(tablespace);
// }
// }
if (statement.getTablespace() != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
sql += " ON " + statement.getTablespace();
} else if (database instanceof DB2Database || database instanceof InformixDatabase) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
return new Sql[] {
new UnparsedSql(sql)
};
}
| public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" ");
buffer.append("(");
boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().size() == 1;
boolean isPrimaryKeyAutoIncrement = false;
Iterator<String> columnIterator = statement.getColumns().iterator();
while (columnIterator.hasNext()) {
String column = columnIterator.next();
buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column));
buffer.append(" ").append(statement.getColumnTypes().get(column));
AutoIncrementConstraint autoIncrementConstraint = null;
for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
autoIncrementConstraint = currentAutoIncrementConstraint;
break;
}
}
boolean isAutoIncrementColumn = autoIncrementConstraint != null;
boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().contains(column);
isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement
|| isPrimaryKeyColumn && isAutoIncrementColumn;
if ((database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyColumn &&
isAutoIncrementColumn) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
buffer.append(" PRIMARY KEY AUTOINCREMENT");
}
if (statement.getDefaultValue(column) != null) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column));
}
buffer.append(" DEFAULT ");
buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database));
}
if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) {
// TODO: check if database supports auto increment on non primary key column
if (database.supportsAutoIncrement()) {
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
} else {
LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName())));
}
}
if (statement.getNotNullColumns().contains(column)) {
buffer.append(" NOT NULL");
} else {
if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) {
if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) {
//don't append null
} else {
buffer.append(" NULL");
}
}
}
if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) {
buffer.append(" PRIMARY KEY");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
// TODO informixdb
if (!( (database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyAutoIncrement) &&
!((database instanceof InformixDatabase) &&
isSinglePrimaryKeyColumn
)) {
// ...skip this code block for sqlite if a single column primary key
// with an autoincrement constraint exists.
// This constraint is added after the column type.
if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) {
if (!(database instanceof InformixDatabase)) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if (database instanceof OracleDatabase &&
statement.getPrimaryKeyConstraint().getTablespace() != null) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) {
referencesString = database.getDefaultSchemaName()+"."+referencesString;
}
buffer.append(" FOREIGN KEY (")
.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
.append(") REFERENCES ")
.append(referencesString);
if (fkConstraint.isDeleteCascade()) {
buffer.append(" ON DELETE CASCADE");
}
if ((database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
if (fkConstraint.isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (fkConstraint.isDeferrable()) {
buffer.append(" DEFERRABLE");
}
buffer.append(",");
}
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(",");
}
// if (constraints != null && constraints.getCheck() != null) {
// buffer.append(constraints.getCheck()).append(" ");
// }
// }
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
// if (StringUtils.trimToNull(tablespace) != null && database.supportsTablespaces()) {
// if (database instanceof MSSQLDatabase) {
// buffer.append(" ON ").append(tablespace);
// } else if (database instanceof DB2Database) {
// buffer.append(" IN ").append(tablespace);
// } else {
// buffer.append(" TABLESPACE ").append(tablespace);
// }
// }
if (statement.getTablespace() != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
sql += " ON " + statement.getTablespace();
} else if (database instanceof DB2Database || database instanceof InformixDatabase) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
return new Sql[] {
new UnparsedSql(sql)
};
}
|
diff --git a/Rania/src/com/game/rania/model/Radar.java b/Rania/src/com/game/rania/model/Radar.java
index 1cbb941..a84db14 100644
--- a/Rania/src/com/game/rania/model/Radar.java
+++ b/Rania/src/com/game/rania/model/Radar.java
@@ -1,279 +1,279 @@
package com.game.rania.model;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.game.rania.Config;
import com.game.rania.RaniaGame;
import com.game.rania.controller.Controllers;
import com.game.rania.controller.LocationController;
import com.game.rania.model.element.Font;
import com.game.rania.model.element.Object;
import com.game.rania.model.element.RegionID;
import com.game.rania.utils.DrawUtils;
public class Radar extends Object
{
private static final int bigCoeff = 4;
private Text textCoord = null, textPlanet = null;
private Text textUsers = null;
private Vector2 posObject = new Vector2();
private Vector2 scaleObject = new Vector2();
private Color colorObject = new Color();
private Player player = null;
private float size;
private TextureRegion sensorRegion, objRegion;
private LocationController locController = Controllers.locController;
public Radar(Player player, float x, float y)
{
super(RegionID.RADAR, x, y);
this.player = player;
sensorRegion = RaniaGame.mView.getTextureRegion(RegionID.RADAR_SENSOR);
objRegion = RaniaGame.mView.getTextureRegion(RegionID.RADAR_OBJECT);
initFrameBuffer();
touchObject = true;
}
private float speedSensor = 150.0f;
private float deltaSensor = 0.0f;
private float alpha = 0.0f;
private boolean smallMode = true;
@Override
public boolean touchUp(float x, float y)
{
if (!visible)
return false;
smallMode = !smallMode;
if (smallMode)
{
RaniaGame.mController.addProcessor(Controllers.locController.getPlayerController());
position.set(savePosition);
scale.div(bigCoeff);
width /= bigCoeff;
height /= bigCoeff;
projMatrix.setToOrtho2D(0, 0, width, height);
frameBuffer = smallFrameBuffer;
regionBuffer = smallRegionBuffer;
}
else
{
RaniaGame.mController.removeProcessor(Controllers.locController.getPlayerController());
player.stop();
savePosition.set(position);
position.set(0, 0);
scale.scl(bigCoeff);
width *= bigCoeff;
height *= bigCoeff;
projMatrix.setToOrtho2D(0, 0, width, height);
frameBuffer = bigFrameBuffer;
regionBuffer = bigRegionBuffer;
}
return true;
}
@Override
public void update(float deltaTime)
{
deltaSensor += deltaTime * speedSensor;
float widthRadar = getWidth();
if (deltaSensor > widthRadar)
deltaSensor -= widthRadar;
textCoord.content = String.format("%d %d", locController.getOutputX(player.position.x), locController.getOutputY(player.position.y));
textUsers.content = String.valueOf(locController.getUsers().size());
}
private FrameBuffer smallFrameBuffer = null, bigFrameBuffer = null, frameBuffer = null;
private TextureRegion smallRegionBuffer = null, bigRegionBuffer = null, regionBuffer = null;
private SpriteBatch spriteBuffer = null;
private ShapeRenderer shapeBuffer = null;
private Vector2 savePosition = new Vector2(0, 0);
private float width, height;
Matrix4 projMatrix = new Matrix4();
private void initFrameBuffer()
{
width = region.getRegionWidth();
height = region.getRegionHeight();
frameBuffer = smallFrameBuffer = new FrameBuffer(Format.RGBA4444, region.getRegionWidth(), region.getRegionHeight(), false);
regionBuffer = smallRegionBuffer = new TextureRegion(smallFrameBuffer.getColorBufferTexture());
smallRegionBuffer.flip(false, true);
bigFrameBuffer = new FrameBuffer(Format.RGBA4444, region.getRegionWidth() * bigCoeff, region.getRegionHeight() * bigCoeff, false);
bigRegionBuffer = new TextureRegion(bigFrameBuffer.getColorBufferTexture());
bigRegionBuffer.flip(false, true);
spriteBuffer = new SpriteBatch();
shapeBuffer = new ShapeRenderer();
projMatrix.setToOrtho2D(0, 0, width, height);
textPlanet = new Text("", Font.getFont("data/fonts/Postmodern One.ttf", 20), color, 0, 0);
textCoord = new Text("", Font.getFont("data/fonts/Postmodern One.ttf", 20), color, width * 0.5f, 20);
textUsers = new Text("", Font.getFont("data/fonts/Postmodern One.ttf", 20), color, width * 0.5f, height - 20);
}
@Override
public boolean draw(SpriteBatch sprite, ShapeRenderer shape)
{
if (!visible || player == null || region == null)
return false;
sprite.end();
frameBuffer.begin();
spriteBuffer.setProjectionMatrix(projMatrix);
shapeBuffer.setProjectionMatrix(projMatrix);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (smallMode)
{
size = player.radar.item.radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
spriteBuffer.end();
if (locController.getStar() != null)
{
posObject.set(locController.getStar().position);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
// orbits
shapeBuffer.begin(ShapeType.Line);
shapeBuffer.setColor(1, 1, 1, 0.75f);
for (Planet planet : locController.getPlanets())
{
DrawUtils.drawDottedCircle(shapeBuffer, posObject.x, posObject.y, planet.orbit * width / size, 4.0f);
}
shapeBuffer.end();
}
spriteBuffer.begin();
if (objRegion != null)
{
if (locController.getStar() != null)
{
colorObject.set(1, 1, 1, 1);
drawRadarObject(locController.getStar(), 0, size);
}
for (Planet planet : locController.getPlanets())
{
colorObject.set(planet.domain.color);
drawRadarObject(planet, 0, size);
}
for (User user : locController.getUsers())
{
colorObject.set(user.domain.color);
drawRadarObject(user, 0.035f, size);
}
}
if (Config.radarNoiseOn && sensorRegion != null)
{
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, sensorRegion, deltaSensor, height * 0.5f, angle, 1, height * 0.98f / sensorRegion.getRegionHeight());
}
textCoord.draw(spriteBuffer, shape);
textUsers.draw(spriteBuffer, shape);
spriteBuffer.end();
}
else
{
size = player.radar.item.big_radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
if (objRegion != null)
{
colorObject.set(1, 1, 1, 1);
for (Location location : locController.getLocations())
{
drawRadarObject(location.x, location.y, 0, 0.04f, 0.04f, size);
posObject.set(location.x, location.y);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
textPlanet.content = location.starName;
textPlanet.draw(spriteBuffer, posObject.x, posObject.y + 25);
textPlanet.content = "(" + locController.getOutputX(location.x) + ", " + locController.getOutputY(location.y) + ")";
textPlanet.draw(spriteBuffer, posObject.x, posObject.y - 25);
}
}
spriteBuffer.end();
}
frameBuffer.end();
sprite.begin();
- colorObject.set(1, 1, 1, 1);
+ sprite.setColor(1, 1, 1, 1);
drawRegion(sprite, regionBuffer, position.x, position.y, 0, 1, 1);
return true;
}
protected void drawRadarObject(Object object, float fixedSize, float gridSize)
{
if (fixedSize == 0)
{
drawRadarObject(object.position.x,
object.position.y,
object.angle,
object.region.getRegionWidth() * object.scale.x / gridSize,
object.region.getRegionHeight() * object.scale.y / gridSize,
gridSize);
}
else
{
drawRadarObject(object.position.x,
object.position.y,
object.angle,
fixedSize,
fixedSize,
gridSize);
}
}
protected void drawRadarObject(float posX, float posY, float angle, float w, float h, float gridSize)
{
posObject.set(posX, posY);
posObject.sub(player.position);
posObject.scl(width / gridSize, height / gridSize);
posObject.add(width * 0.5f, height * 0.5f);
scaleObject.set(w, h);
scaleObject.scl(width / objRegion.getRegionWidth(),
height / objRegion.getRegionHeight());
if (Config.radarNoiseOn)
{
alpha = (deltaSensor - posObject.x) / width;
if (alpha < 0)
alpha += 1.0f;
colorObject.a = 1.0f - 0.5f * alpha;
}
spriteBuffer.setColor(colorObject);
drawRegion(spriteBuffer, objRegion, posObject, angle, scaleObject);
}
}
| true | true | public boolean draw(SpriteBatch sprite, ShapeRenderer shape)
{
if (!visible || player == null || region == null)
return false;
sprite.end();
frameBuffer.begin();
spriteBuffer.setProjectionMatrix(projMatrix);
shapeBuffer.setProjectionMatrix(projMatrix);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (smallMode)
{
size = player.radar.item.radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
spriteBuffer.end();
if (locController.getStar() != null)
{
posObject.set(locController.getStar().position);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
// orbits
shapeBuffer.begin(ShapeType.Line);
shapeBuffer.setColor(1, 1, 1, 0.75f);
for (Planet planet : locController.getPlanets())
{
DrawUtils.drawDottedCircle(shapeBuffer, posObject.x, posObject.y, planet.orbit * width / size, 4.0f);
}
shapeBuffer.end();
}
spriteBuffer.begin();
if (objRegion != null)
{
if (locController.getStar() != null)
{
colorObject.set(1, 1, 1, 1);
drawRadarObject(locController.getStar(), 0, size);
}
for (Planet planet : locController.getPlanets())
{
colorObject.set(planet.domain.color);
drawRadarObject(planet, 0, size);
}
for (User user : locController.getUsers())
{
colorObject.set(user.domain.color);
drawRadarObject(user, 0.035f, size);
}
}
if (Config.radarNoiseOn && sensorRegion != null)
{
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, sensorRegion, deltaSensor, height * 0.5f, angle, 1, height * 0.98f / sensorRegion.getRegionHeight());
}
textCoord.draw(spriteBuffer, shape);
textUsers.draw(spriteBuffer, shape);
spriteBuffer.end();
}
else
{
size = player.radar.item.big_radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
if (objRegion != null)
{
colorObject.set(1, 1, 1, 1);
for (Location location : locController.getLocations())
{
drawRadarObject(location.x, location.y, 0, 0.04f, 0.04f, size);
posObject.set(location.x, location.y);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
textPlanet.content = location.starName;
textPlanet.draw(spriteBuffer, posObject.x, posObject.y + 25);
textPlanet.content = "(" + locController.getOutputX(location.x) + ", " + locController.getOutputY(location.y) + ")";
textPlanet.draw(spriteBuffer, posObject.x, posObject.y - 25);
}
}
spriteBuffer.end();
}
frameBuffer.end();
sprite.begin();
colorObject.set(1, 1, 1, 1);
drawRegion(sprite, regionBuffer, position.x, position.y, 0, 1, 1);
return true;
}
| public boolean draw(SpriteBatch sprite, ShapeRenderer shape)
{
if (!visible || player == null || region == null)
return false;
sprite.end();
frameBuffer.begin();
spriteBuffer.setProjectionMatrix(projMatrix);
shapeBuffer.setProjectionMatrix(projMatrix);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (smallMode)
{
size = player.radar.item.radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
spriteBuffer.end();
if (locController.getStar() != null)
{
posObject.set(locController.getStar().position);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
// orbits
shapeBuffer.begin(ShapeType.Line);
shapeBuffer.setColor(1, 1, 1, 0.75f);
for (Planet planet : locController.getPlanets())
{
DrawUtils.drawDottedCircle(shapeBuffer, posObject.x, posObject.y, planet.orbit * width / size, 4.0f);
}
shapeBuffer.end();
}
spriteBuffer.begin();
if (objRegion != null)
{
if (locController.getStar() != null)
{
colorObject.set(1, 1, 1, 1);
drawRadarObject(locController.getStar(), 0, size);
}
for (Planet planet : locController.getPlanets())
{
colorObject.set(planet.domain.color);
drawRadarObject(planet, 0, size);
}
for (User user : locController.getUsers())
{
colorObject.set(user.domain.color);
drawRadarObject(user, 0.035f, size);
}
}
if (Config.radarNoiseOn && sensorRegion != null)
{
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, sensorRegion, deltaSensor, height * 0.5f, angle, 1, height * 0.98f / sensorRegion.getRegionHeight());
}
textCoord.draw(spriteBuffer, shape);
textUsers.draw(spriteBuffer, shape);
spriteBuffer.end();
}
else
{
size = player.radar.item.big_radius;
spriteBuffer.begin();
spriteBuffer.setColor(color);
drawRegion(spriteBuffer, region, width * 0.5f, height * 0.5f, angle, scale.x, scale.y);
if (objRegion != null)
{
colorObject.set(1, 1, 1, 1);
for (Location location : locController.getLocations())
{
drawRadarObject(location.x, location.y, 0, 0.04f, 0.04f, size);
posObject.set(location.x, location.y);
posObject.sub(player.position);
posObject.scl(width / size, height / size);
posObject.add(width * 0.5f, height * 0.5f);
textPlanet.content = location.starName;
textPlanet.draw(spriteBuffer, posObject.x, posObject.y + 25);
textPlanet.content = "(" + locController.getOutputX(location.x) + ", " + locController.getOutputY(location.y) + ")";
textPlanet.draw(spriteBuffer, posObject.x, posObject.y - 25);
}
}
spriteBuffer.end();
}
frameBuffer.end();
sprite.begin();
sprite.setColor(1, 1, 1, 1);
drawRegion(sprite, regionBuffer, position.x, position.y, 0, 1, 1);
return true;
}
|
diff --git a/src/ise/gameoflife/enviroment/Environment.java b/src/ise/gameoflife/enviroment/Environment.java
index 290fbc3..740ad8a 100644
--- a/src/ise/gameoflife/enviroment/Environment.java
+++ b/src/ise/gameoflife/enviroment/Environment.java
@@ -1,129 +1,129 @@
package ise.gameoflife.enviroment;
import ise.gameoflife.AbstractAgent;
import ise.gameoflife.enviroment.actionhandlers.HuntHandler;
import ise.gameoflife.tokens.RegistrationRequest;
import ise.gameoflife.tokens.RegistrationResponse;
import java.util.UUID;
import org.simpleframework.xml.Element;
import presage.Action;
import presage.EnvDataModel;
import presage.EnvironmentConnector;
import presage.Input;
import presage.Participant;
import presage.Simulation;
import presage.environment.AbstractEnvironment;
import presage.environment.messages.ENVDeRegisterRequest;
import presage.environment.messages.ENVRegisterRequest;
import presage.environment.messages.ENVRegistrationResponse;
/**
* The primary environment code for the GameOfLife that we define. This will
* contain a list of all the groups, food etc. etc. that exist in
* @author Benedict Harcourt
*/
public class Environment extends AbstractEnvironment
{
static public abstract class ActionHandler implements AbstractEnvironment.ActionHandler
{
@Override abstract public boolean canHandle(Action action);
@Override abstract public Input handle(Action action, String actorID);
}
@Element
protected EnvironmentDataModel dmodel;
/**
* A reference to the simulation that we're part of, for the purpose of
* adding participants etc.
*/
protected Simulation sim;
@Deprecated
public Environment()
{
super();
}
@presage.annotations.EnvironmentConstructor( { "queueactions",
"randomseed", "dmodel" })
public Environment(boolean queueactions, long randomseed,
EnvironmentDataModel dmodel) {
super(queueactions, randomseed);
// Separation of data from code!
this.dmodel = dmodel;
}
@Override
public boolean deregister(ENVDeRegisterRequest deregistrationObject)
{
if (!authenticator.get(deregistrationObject.getParticipantID()).equals(deregistrationObject.getParticipantAuthCode()))
{
return false;
}
return dmodel.removeParticipant(deregistrationObject.getParticipantID());
}
@Override
public ENVRegistrationResponse onRegister(ENVRegisterRequest registrationObject)
{
final RegistrationRequest obj = (RegistrationRequest)registrationObject;
if (!dmodel.registerParticipant(obj)) return null;
return new RegistrationResponse(obj.getParticipantID(), UUID.randomUUID(), new EnvConnector(this));
}
@Override
public EnvDataModel getDataModel()
{
return dmodel;
}
@Override
protected void onInitialise(Simulation sim)
{
this.sim = sim;
// TODO: Add message handlers
this.actionhandlers.add(new HuntHandler(this));
}
@Override
protected void updatePerceptions()
{
// FIXME: Write this function
//throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected void updatePhysicalWorld()
{
- for (Participant agent : sim.players)
+ for (Participant agent : sim.players.values())
{
if (sim.isParticipantActive(agent.getId()))
{
if (agent instanceof ise.gameoflife.AbstractAgent)
{
// TODO: Put a consume food result here when this is complete
agent.enqueueInput((Input)null);
}
}
}
// FIXME: Write this function
//throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected void updateNetwork()
{
// FIXME: Write this function
//throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTime(long cycle)
{
this.dmodel.setTime(cycle);
}
}
| true | true | protected void updatePhysicalWorld()
{
for (Participant agent : sim.players)
{
if (sim.isParticipantActive(agent.getId()))
{
if (agent instanceof ise.gameoflife.AbstractAgent)
{
// TODO: Put a consume food result here when this is complete
agent.enqueueInput((Input)null);
}
}
}
// FIXME: Write this function
//throw new UnsupportedOperationException("Not supported yet.");
}
| protected void updatePhysicalWorld()
{
for (Participant agent : sim.players.values())
{
if (sim.isParticipantActive(agent.getId()))
{
if (agent instanceof ise.gameoflife.AbstractAgent)
{
// TODO: Put a consume food result here when this is complete
agent.enqueueInput((Input)null);
}
}
}
// FIXME: Write this function
//throw new UnsupportedOperationException("Not supported yet.");
}
|
diff --git a/src/autosaveworld/config/AutoSaveConfigMSG.java b/src/autosaveworld/config/AutoSaveConfigMSG.java
index 45f2181..c21cf59 100644
--- a/src/autosaveworld/config/AutoSaveConfigMSG.java
+++ b/src/autosaveworld/config/AutoSaveConfigMSG.java
@@ -1,106 +1,106 @@
/**
*
* Copyright 2012 Shevchik
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package autosaveworld.config;
import java.io.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class AutoSaveConfigMSG {
private FileConfiguration configmsg;
private AutoSaveConfig config;
public AutoSaveConfigMSG(AutoSaveConfig config) {
this.config = config;
}
// Messages
public String messageBroadcastPre = "&9AutoSaving";
public String messageBroadcastPost = "&9AutoSave Complete";
public String messageInsufficientPermissions = "&cYou do not have access to that command.";
public String messageWarning = "&9Warning, AutoSave will commence soon.";
public String messageBroadcastBackupPre = "&9AutoBackuping";
public String messageBroadcastBackupPost = "&9AutoBackup Complete";
public String messageBackupWarning = "&9Warning, AutoBackup will commence soon";
public String messagePurgePre = "&9AutoPurging";
public String messagePurgePost = "&9AutoPurge Complete";
public String messageAutoRestart = "&9Server is restarting";
public String messageAutoRestartCountdown = "&9Server will restart in {SECONDS} seconds";
public String messageWorldRegenKick = "&9Server is regenerating map, please come back later";
public void loadmsg() {
if (!config.switchtolangfile) {
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg.yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
messageWorldRegenKick = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
configmsg = new YamlConfiguration();
configmsg.set("broadcast.pre", messageBroadcastPre);
configmsg.set("broadcast.post", messageBroadcastPost);
configmsg.set("broadcastbackup.pre", messageBroadcastBackupPre);
configmsg.set("broadcastbackup.post", messageBroadcastBackupPost);
configmsg.set("broadcastpurge.pre", messagePurgePre);
configmsg.set("broadcastpurge.post", messagePurgePost);
configmsg.set("warning.save", messageWarning);
configmsg.set("warning.backup", messageBackupWarning);
configmsg.set("insufficentpermissions", messageInsufficientPermissions);
configmsg.set("autorestart.restarting",messageAutoRestart);
configmsg.set("autorestart.countdown",messageAutoRestartCountdown);
configmsg.set("worldregen.kickmessage", messageWorldRegenKick);
try {
configmsg.save(new File("plugins/AutoSaveWorld/configmsg.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
{
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg_"+config.langfilesuffix+".yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
- messageAutoRestartCountdown = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
+ messageWorldRegenKick = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
}
}
}
| true | true | public void loadmsg() {
if (!config.switchtolangfile) {
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg.yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
messageWorldRegenKick = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
configmsg = new YamlConfiguration();
configmsg.set("broadcast.pre", messageBroadcastPre);
configmsg.set("broadcast.post", messageBroadcastPost);
configmsg.set("broadcastbackup.pre", messageBroadcastBackupPre);
configmsg.set("broadcastbackup.post", messageBroadcastBackupPost);
configmsg.set("broadcastpurge.pre", messagePurgePre);
configmsg.set("broadcastpurge.post", messagePurgePost);
configmsg.set("warning.save", messageWarning);
configmsg.set("warning.backup", messageBackupWarning);
configmsg.set("insufficentpermissions", messageInsufficientPermissions);
configmsg.set("autorestart.restarting",messageAutoRestart);
configmsg.set("autorestart.countdown",messageAutoRestartCountdown);
configmsg.set("worldregen.kickmessage", messageWorldRegenKick);
try {
configmsg.save(new File("plugins/AutoSaveWorld/configmsg.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
{
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg_"+config.langfilesuffix+".yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
messageAutoRestartCountdown = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
}
}
| public void loadmsg() {
if (!config.switchtolangfile) {
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg.yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
messageWorldRegenKick = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
configmsg = new YamlConfiguration();
configmsg.set("broadcast.pre", messageBroadcastPre);
configmsg.set("broadcast.post", messageBroadcastPost);
configmsg.set("broadcastbackup.pre", messageBroadcastBackupPre);
configmsg.set("broadcastbackup.post", messageBroadcastBackupPost);
configmsg.set("broadcastpurge.pre", messagePurgePre);
configmsg.set("broadcastpurge.post", messagePurgePost);
configmsg.set("warning.save", messageWarning);
configmsg.set("warning.backup", messageBackupWarning);
configmsg.set("insufficentpermissions", messageInsufficientPermissions);
configmsg.set("autorestart.restarting",messageAutoRestart);
configmsg.set("autorestart.countdown",messageAutoRestartCountdown);
configmsg.set("worldregen.kickmessage", messageWorldRegenKick);
try {
configmsg.save(new File("plugins/AutoSaveWorld/configmsg.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
{
configmsg = YamlConfiguration.loadConfiguration(new File("plugins/AutoSaveWorld/configmsg_"+config.langfilesuffix+".yml"));
messageBroadcastPre =configmsg.getString("broadcast.pre", messageBroadcastPre);
messageBroadcastPost =configmsg.getString("broadcast.post", messageBroadcastPost);
messageBroadcastBackupPre =configmsg.getString("broadcastbackup.pre", messageBroadcastBackupPre);
messageBroadcastBackupPost =configmsg.getString("broadcastbackup.post", messageBroadcastBackupPost);
messagePurgePre =configmsg.getString("broadcastpurge.pre", messagePurgePre);
messagePurgePost =configmsg.getString("broadcastpurge.post", messagePurgePost);
messageWarning =configmsg.getString("warning.save", messageWarning);
messageBackupWarning =configmsg.getString("warning.backup", messageBackupWarning);
messageInsufficientPermissions =configmsg.getString("insufficentpermissions", messageInsufficientPermissions);
messageAutoRestart = configmsg.getString("autorestart.restarting",messageAutoRestart);
messageAutoRestartCountdown = configmsg.getString("autorestart.countdown",messageAutoRestartCountdown);
messageWorldRegenKick = configmsg.getString("worldregen.kickmessage", messageWorldRegenKick);
}
}
|
diff --git a/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapService.java b/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapService.java
index d62d4fe00c..e5ccf83081 100644
--- a/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapService.java
+++ b/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapService.java
@@ -1,1218 +1,1218 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.ldap;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.partition.PartitionNexus;
import org.apache.directory.server.core.security.CoreKeyStoreSpi;
import org.apache.directory.server.ldap.handlers.LdapRequestHandler;
import org.apache.directory.server.ldap.handlers.AbandonHandler;
import org.apache.directory.server.ldap.handlers.AddHandler;
import org.apache.directory.server.ldap.handlers.BindHandler;
import org.apache.directory.server.ldap.handlers.CompareHandler;
import org.apache.directory.server.ldap.handlers.DeleteHandler;
import org.apache.directory.server.ldap.handlers.ExtendedHandler;
import org.apache.directory.server.ldap.handlers.ModifyDnHandler;
import org.apache.directory.server.ldap.handlers.ModifyHandler;
import org.apache.directory.server.ldap.handlers.SearchHandler;
import org.apache.directory.server.ldap.handlers.UnbindHandler;
import org.apache.directory.server.ldap.handlers.bind.MechanismHandler;
import org.apache.directory.server.ldap.handlers.ssl.LdapsInitializer;
import org.apache.directory.server.ldap.replication.ReplicationSystem;
import org.apache.directory.server.protocol.shared.DirectoryBackedService;
import org.apache.directory.shared.ldap.constants.SaslQoP;
import org.apache.directory.shared.ldap.exception.LdapConfigurationException;
import org.apache.directory.shared.ldap.message.InternalAbandonRequest;
import org.apache.directory.shared.ldap.message.InternalAddRequest;
import org.apache.directory.shared.ldap.message.InternalBindRequest;
import org.apache.directory.shared.ldap.message.InternalCompareRequest;
import org.apache.directory.shared.ldap.message.InternalDeleteRequest;
import org.apache.directory.shared.ldap.message.InternalExtendedRequest;
import org.apache.directory.shared.ldap.message.InternalModifyDnRequest;
import org.apache.directory.shared.ldap.message.InternalModifyRequest;
import org.apache.directory.shared.ldap.message.InternalSearchRequest;
import org.apache.directory.shared.ldap.message.InternalUnbindRequest;
import org.apache.directory.shared.ldap.message.control.CascadeControl;
import org.apache.directory.shared.ldap.message.control.EntryChangeControl;
import org.apache.directory.shared.ldap.message.control.ManageDsaITControl;
import org.apache.directory.shared.ldap.message.control.PagedSearchControl;
import org.apache.directory.shared.ldap.message.control.PersistentSearchControl;
import org.apache.directory.shared.ldap.message.control.SubentriesControl;
import org.apache.directory.shared.ldap.message.control.replication.SyncDoneValueControl;
import org.apache.directory.shared.ldap.message.control.replication.SyncInfoValueControl;
import org.apache.directory.shared.ldap.message.control.replication.SyncRequestValueControl;
import org.apache.directory.shared.ldap.message.control.replication.SyncStateValueControl;
import org.apache.directory.shared.ldap.message.extended.NoticeOfDisconnect;
import org.apache.directory.shared.ldap.util.StringTools;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.filterchain.IoFilterChainBuilder;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoEventType;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import org.apache.mina.handler.demux.MessageHandler;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An LDAP protocol provider implementation which dynamically associates
* handlers.
*
* @org.apache.xbean.XBean
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev: 688548 $
*/
public class LdapService extends DirectoryBackedService
{
/** Value (0) for configuration where size limit is unlimited. */
public static final int NO_SIZE_LIMIT = 0;
/** Value (0) for configuration where time limit is unlimited. */
public static final int NO_TIME_LIMIT = 0;
/** the constant service name of this ldap protocol provider **/
public static final String SERVICE_NAME = "ldap";
private static final long serialVersionUID = 3757127143811666817L;
/** logger for this class */
private static final Logger LOG = LoggerFactory.getLogger( LdapService.class.getName() );
/** The default maximum size limit. */
private static final int MAX_SIZE_LIMIT_DEFAULT = 100;
/** The default maximum time limit. */
private static final int MAX_TIME_LIMIT_DEFAULT = 10000;
/** The default service pid. */
private static final String SERVICE_PID_DEFAULT = "org.apache.directory.server.ldap";
/** The default service name. */
private static final String SERVICE_NAME_DEFAULT = "ApacheDS LDAP Service";
/** The default IP port. */
private static final int IP_PORT_DEFAULT = 389;
/** the session manager for this LdapService */
private LdapSessionManager ldapSessionManager = new LdapSessionManager();
/** a set of supported controls */
private Set<String> supportedControls;
/**
* The maximum size limit.
* @see {@link LdapService#MAX_SIZE_LIMIT_DEFAULT }
*/
private int maxSizeLimit = MAX_SIZE_LIMIT_DEFAULT;
/**
* The maximum time limit.
* @see {@link LdapService#MAX_TIME_LIMIT_DEFAULT }
*/
private int maxTimeLimit = MAX_TIME_LIMIT_DEFAULT;
/** Whether LDAPS is enabled: disabled by default. */
private boolean enableLdaps;
/** If LDAPS is activated : the external Keystore file, if defined */
private String keystoreFile;
/** If LDAPS is activated : the certificate password */
private String certificatePassword;
/** Whether to allow anonymous access: enabled by default. */
private boolean allowAnonymousAccess = true;
/** The extended operation handlers. */
private final Collection<ExtendedOperationHandler> extendedOperationHandlers =
new ArrayList<ExtendedOperationHandler>();
/** The supported authentication mechanisms. */
private Map<String, MechanismHandler> saslMechanismHandlers =
new HashMap<String, MechanismHandler>();
/** The name of this host, validated during SASL negotiation. */
private String saslHost = "ldap.example.com";
/** The service principal, used by GSSAPI. */
private String saslPrincipal = "ldap/[email protected]";
/** The quality of protection (QoP), used by DIGEST-MD5 and GSSAPI. */
private Set<String> saslQop;
private String saslQopString;
/** The list of realms serviced by this host. */
private List<String> saslRealms;
/** The potocol handlers */
private LdapRequestHandler<InternalAbandonRequest> abandonHandler;
private LdapRequestHandler<InternalAddRequest> addHandler;
private LdapRequestHandler<InternalBindRequest> bindHandler;
private LdapRequestHandler<InternalCompareRequest> compareHandler;
private LdapRequestHandler<InternalDeleteRequest> deleteHandler;
private LdapRequestHandler<InternalExtendedRequest> extendedHandler;
private LdapRequestHandler<InternalModifyRequest> modifyHandler;
private LdapRequestHandler<InternalModifyDnRequest> modifyDnHandler;
private LdapRequestHandler<InternalSearchRequest> searchHandler;
private LdapRequestHandler<InternalUnbindRequest> unbindHandler;
/** the underlying provider codec factory */
private ProtocolCodecFactory codecFactory;
/** the MINA protocol handler */
private final LdapProtocolHandler handler = new LdapProtocolHandler(this);
/** tracks start state of the server */
private boolean started;
/**
* Whether or not confidentiality (TLS secured connection) is required:
* disabled by default.
*/
private boolean confidentialityRequired;
private ReplicationSystem replicationSystem;
/**
* Creates an LDAP protocol provider.
*/
public LdapService()
{
super.setEnabled( true );
super.setServiceId( SERVICE_PID_DEFAULT );
super.setServiceName( SERVICE_NAME_DEFAULT );
saslQop = new HashSet<String>();
saslQop.add( SaslQoP.QOP_AUTH );
saslQop.add( SaslQoP.QOP_AUTH_INT );
saslQop.add( SaslQoP.QOP_AUTH_CONF );
saslQopString = SaslQoP.QOP_AUTH + ',' + SaslQoP.QOP_AUTH_INT + ',' + SaslQoP.QOP_AUTH_CONF;
saslRealms = new ArrayList<String>();
saslRealms.add( "example.com" );
this.supportedControls = new HashSet<String>();
this.supportedControls.add( PersistentSearchControl.CONTROL_OID );
this.supportedControls.add( EntryChangeControl.CONTROL_OID );
this.supportedControls.add( SubentriesControl.CONTROL_OID );
this.supportedControls.add( ManageDsaITControl.CONTROL_OID );
this.supportedControls.add( CascadeControl.CONTROL_OID );
this.supportedControls.add( PagedSearchControl.CONTROL_OID );
// Replication controls
this.supportedControls.add( SyncDoneValueControl.CONTROL_OID );
this.supportedControls.add( SyncInfoValueControl.CONTROL_OID );
this.supportedControls.add( SyncRequestValueControl.CONTROL_OID );
this.supportedControls.add( SyncStateValueControl.CONTROL_OID );
}
/**
* Install the LDAP request handlers.
*/
private void installDefaultHandlers()
{
if ( getAbandonHandler() == null )
{
setAbandonHandler( new AbandonHandler() );
}
if ( getAddHandler() == null )
{
setAddHandler( new AddHandler() );
}
if ( getBindHandler() == null )
{
BindHandler handler = new BindHandler();
handler.setSaslMechanismHandlers( saslMechanismHandlers );
setBindHandler( handler );
}
if ( getCompareHandler() == null )
{
setCompareHandler( new CompareHandler() );
}
if ( getDeleteHandler() == null )
{
setDeleteHandler( new DeleteHandler() );
}
if ( getExtendedHandler() == null )
{
setExtendedHandler( new ExtendedHandler() );
}
if ( getModifyHandler() == null )
{
setModifyHandler( new ModifyHandler() );
}
if ( getModifyDnHandler() == null )
{
setModifyDnHandler( new ModifyDnHandler() );
}
if ( getSearchHandler() == null )
{
setSearchHandler( new SearchHandler() );
}
if ( getUnbindHandler() == null )
{
setUnbindHandler( new UnbindHandler() );
}
}
/**
* @throws IOException if we cannot bind to the specified port
* @throws NamingException if the LDAP server cannot be started
*/
public void start() throws Exception
{
if ( ! isEnabled() )
{
return;
}
IoFilterChainBuilder chain;
if ( isEnableLdaps() )
{
KeyStore keyStore = null;
if ( StringTools.isEmpty( keystoreFile ) )
{
Provider provider = Security.getProvider( "SUN" );
LOG.debug( "provider = {}", provider );
CoreKeyStoreSpi coreKeyStoreSpi = new CoreKeyStoreSpi( getDirectoryService() );
keyStore = new KeyStore( coreKeyStoreSpi, provider, "JKS" ) {};
try
{
keyStore.load( null, null );
}
catch ( Exception e )
{
// nothing really happens with this keystore
}
}
else
{
keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
FileInputStream fis = new FileInputStream( keystoreFile );
keyStore.load( fis, null );
}
chain = LdapsInitializer.init( keyStore, certificatePassword );
}
else
{
chain = new DefaultIoFilterChainBuilder();
}
// Inject the codec into the chain
((DefaultIoFilterChainBuilder)chain).addLast( "codec",
new ProtocolCodecFilter( this.getProtocolCodecFactory() ) );
// Now inject an ExecutorFilter for the write operations
// We use the same number of thread than the number of IoProcessor
// (NOTE : this has to be double checked)
((DefaultIoFilterChainBuilder)chain).addLast( "executor",
- new ExecutorFilter( new OrderedThreadPoolExecutor( getTcpTransport().getNbThreads() ),
- IoEventType.WRITE ) );
+ new ExecutorFilter(
+ new OrderedThreadPoolExecutor( getTcpTransport().getNbThreads() ) ) );
/*
* The server is now initialized, we can
* install the default requests handlers, which need
* access to the DirectoryServer instance.
*/
installDefaultHandlers();
startNetwork(
getTcpTransport().getAddress(),
getTcpTransport().getPort(),
getTcpTransport().getBackLog(), chain );
started = true;
if ( isEnableLdaps() )
{
LOG.info( "Ldaps service started." );
System.out.println( "Ldaps service started." );
}
else
{
LOG.info( "Ldap service started." );
System.out.println( "Ldap service started." );
}
}
public void stop()
{
try
{
// we should unbind the service before we begin sending the notice
// of disconnect so new connections are not formed while we process
List<WriteFuture> writeFutures = new ArrayList<WriteFuture>();
// If the socket has already been unbound as with a successful
// GracefulShutdownRequest then this will complain that the service
// is not bound - this is ok because the GracefulShutdown has already
// sent notices to to the existing active sessions
List<IoSession> sessions;
try
{
sessions = new ArrayList<IoSession>(
getSocketAcceptor().getManagedSessions().values() );
}
catch ( IllegalArgumentException e )
{
LOG.warn( "Seems like the LDAP service (" + getPort() + ") has already been unbound." );
return;
}
getSocketAcceptor().dispose();
if ( LOG.isInfoEnabled() )
{
LOG.info( "Unbind of an LDAP service (" + getPort() + ") is complete." );
LOG.info( "Sending notice of disconnect to existing clients sessions." );
}
// Send Notification of Disconnection messages to all connected clients.
if ( sessions != null )
{
for ( IoSession session:sessions )
{
writeFutures.add( session.write( NoticeOfDisconnect.UNAVAILABLE ) );
}
}
// And close the connections when the NoDs are sent.
Iterator<IoSession> sessionIt = sessions.iterator();
for ( WriteFuture future:writeFutures )
{
future.await( 1000L );
sessionIt.next().close( true );
}
}
catch ( Exception e )
{
LOG.warn( "Failed to sent NoD.", e );
}
if ( isEnableLdaps() )
{
LOG.info( "Ldaps service stopped." );
System.out.println( "Ldaps service stopped." );
}
else
{
LOG.info( "Ldap service stopped." );
System.out.println( "Ldap service stopped." );
}
}
private void startNetwork( String hostname, int port,int backlog, IoFilterChainBuilder chainBuilder )
throws Exception
{
if ( backlog < 0 )
{
// Set the baclog to the default value when it's below 0
backlog = 50;
}
PartitionNexus nexus = getDirectoryService().getPartitionNexus();
for ( ExtendedOperationHandler h : extendedOperationHandlers )
{
LOG.info( "Added Extended Request Handler: " + h.getOid() );
h.setLdapServer( this );
nexus.registerSupportedExtensions( h.getExtensionOids() );
}
nexus.registerSupportedSaslMechanisms( saslMechanismHandlers.keySet() );
try
{
SocketAcceptor acceptor = getSocketAcceptor();
// Now, configure the acceptor
// Disable the disconnection of the clients on unbind
acceptor.setCloseOnDeactivation( false );
// Allow the port to be reused even if the socket is in TIME_WAIT state
acceptor.setReuseAddress( true );
// No Nagle's algorithm
acceptor.getSessionConfig().setTcpNoDelay( true );
// Inject the chain
acceptor.setFilterChainBuilder( chainBuilder );
// Inject the protocol handler
acceptor.setHandler( getHandler() );
// Bind to the configured address
acceptor.bind();
// We are done !
started = true;
if ( LOG.isInfoEnabled() )
{
LOG.info( "Successful bind of an LDAP Service (" + port + ") is complete." );
}
}
catch ( IOException e )
{
String msg = "Failed to bind an LDAP service (" + port + ") to the service registry.";
LdapConfigurationException lce = new LdapConfigurationException( msg );
lce.setRootCause( e );
LOG.error( msg, e );
throw lce;
}
}
public String getName()
{
return SERVICE_NAME;
}
public IoHandler getHandler()
{
return handler;
}
public LdapSessionManager getLdapSessionManager()
{
return ldapSessionManager;
}
public ProtocolCodecFactory getProtocolCodecFactory()
{
return codecFactory;
}
// ------------------------------------------------------------------------
// Configuration Methods
// ------------------------------------------------------------------------
/**
* Registeres the specified {@link ExtendedOperationHandler} to this
* protocol provider to provide a specific LDAP extended operation.
*
* @param eoh an extended operation handler
* @throws NamingException on failure to add the handler
*/
public void addExtendedOperationHandler( ExtendedOperationHandler eoh ) throws Exception
{
if ( started )
{
eoh.setLdapServer( this );
PartitionNexus nexus = getDirectoryService().getPartitionNexus();
nexus.registerSupportedExtensions( eoh.getExtensionOids() );
}
else
{
extendedOperationHandlers.add( eoh );
}
}
/**
* Deregisteres an {@link ExtendedOperationHandler} with the specified <tt>oid</tt>
* from this protocol provider.
*
* @param oid the numeric identifier for the extended operation associated with
* the handler to remove
*/
public void removeExtendedOperationHandler( String oid )
{
// need to do something like this to make this work right
// PartitionNexus nexus = getDirectoryService().getPartitionNexus();
// nexus.unregisterSupportedExtensions( eoh.getExtensionOids() );
ExtendedOperationHandler handler = null;
for ( ExtendedOperationHandler h : extendedOperationHandlers )
{
if ( h.getOid().equals( oid ) )
{
handler = h;
break;
}
}
extendedOperationHandlers.remove( handler );
}
/**
* Returns an {@link ExtendedOperationHandler} with the specified <tt>oid</tt>
* which is registered to this protocol provider.
*
* @param oid the oid of the extended request of associated with the extended
* request handler
* @return the exnteded operation handler
*/
public ExtendedOperationHandler getExtendedOperationHandler( String oid )
{
for ( ExtendedOperationHandler h : extendedOperationHandlers )
{
if ( h.getOid().equals( oid ) )
{
return h;
}
}
return null;
}
/**
* Sets the mode for this LdapService to accept requests with or without a
* TLS secured connection via either StartTLS extended operations or using
* LDAPS.
*
* @param confidentialityRequired true to require confidentiality
*/
public void setConfidentialityRequired( boolean confidentialityRequired )
{
this.confidentialityRequired = confidentialityRequired;
}
/**
* Gets whether or not TLS secured connections are required to perform
* operations on this LdapService.
*
* @return true if TLS secured connections are required, false otherwise
*/
public boolean isConfidentialityRequired()
{
return confidentialityRequired;
}
/**
* Returns <tt>true</tt> if LDAPS is enabled.
*
* @return True if LDAPS is enabled.
*/
public boolean isEnableLdaps()
{
return enableLdaps;
}
/**
* Sets if LDAPS is enabled or not.
*
* @param enableLdaps Whether LDAPS is enabled.
*/
public void setEnableLdaps( boolean enableLdaps )
{
this.enableLdaps = enableLdaps;
}
/**
* Returns <code>true</code> if anonymous access is allowed.
*
* @return True if anonymous access is allowed.
*/
public boolean isAllowAnonymousAccess()
{
return allowAnonymousAccess;
}
/**
* Sets whether to allow anonymous access or not.
*
* @param enableAnonymousAccess Set <code>true</code> to allow anonymous access.
*/
public void setAllowAnonymousAccess( boolean enableAnonymousAccess )
{
this.allowAnonymousAccess = enableAnonymousAccess;
}
/**
* Sets the maximum size limit in number of entries to return for search.
*
* @param maxSizeLimit the maximum number of entries to return for search
*/
public void setMaxSizeLimit( int maxSizeLimit )
{
this.maxSizeLimit = maxSizeLimit;
}
/**
* Returns the maximum size limit in number of entries to return for search.
*
* @return The maximum size limit.
*/
public int getMaxSizeLimit()
{
return maxSizeLimit;
}
/**
* Sets the maximum time limit in milliseconds to conduct a search.
*
* @param maxTimeLimit the maximum length of time in milliseconds for search
*/
public void setMaxTimeLimit( int maxTimeLimit )
{
this.maxTimeLimit = maxTimeLimit;
}
/**
* Returns the maximum time limit in milliseconds to conduct a search.
*
* @return The maximum time limit in milliseconds for search
*/
public int getMaxTimeLimit()
{
return maxTimeLimit;
}
/**
* Gets the {@link ExtendedOperationHandler}s.
*
* @return A collection of {@link ExtendedOperationHandler}s.
*/
public Collection<ExtendedOperationHandler> getExtendedOperationHandlers()
{
return new ArrayList<ExtendedOperationHandler>( extendedOperationHandlers );
}
/**
* Sets the {@link ExtendedOperationHandler}s.
*
* @org.apache.xbean.Property nestedType="org.apache.directory.server.ldap.ExtendedOperationHandler"
*
* @param handlers A collection of {@link ExtendedOperationHandler}s.
*/
public void setExtendedOperationHandlers( Collection<ExtendedOperationHandler> handlers )
{
this.extendedOperationHandlers.clear();
this.extendedOperationHandlers.addAll( handlers );
}
/**
* Returns the FQDN of this SASL host, validated during SASL negotiation.
*
* @return The FQDN of this SASL host, validated during SASL negotiation.
*/
public String getSaslHost()
{
return saslHost;
}
/**
* Sets the FQDN of this SASL host, validated during SASL negotiation.
*
* @param saslHost The FQDN of this SASL host, validated during SASL negotiation.
*/
public void setSaslHost( String saslHost )
{
this.saslHost = saslHost;
}
/**
* Returns the Kerberos principal name for this LDAP service, used by GSSAPI.
*
* @return The Kerberos principal name for this LDAP service, used by GSSAPI.
*/
public String getSaslPrincipal()
{
return saslPrincipal;
}
/**
* Sets the Kerberos principal name for this LDAP service, used by GSSAPI.
*
* @param saslPrincipal The Kerberos principal name for this LDAP service, used by GSSAPI.
*/
public void setSaslPrincipal( String saslPrincipal )
{
this.saslPrincipal = saslPrincipal;
}
/**
* Returns the quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*
* @return The quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*/
public String getSaslQopString()
{
return saslQopString;
}
/**
* Returns the Set of quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*
* @return The quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*/
public Set<String> getSaslQop()
{
return saslQop;
}
/**
* Sets the desired quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*
* We build a string from this list, where QoP are comma delimited
*
* @org.apache.xbean.Property nestedType="java.lang.String"
*
* @param saslQop The desired quality-of-protection, used by DIGEST-MD5 and GSSAPI.
*/
public void setSaslQop( Set<String> saslQop )
{
StringBuilder qopList = new StringBuilder();
boolean isFirst = true;
for ( String qop:saslQop )
{
if ( isFirst )
{
isFirst = false;
}
else
{
qopList.append( ',' );
}
qopList.append( qop );
}
this.saslQopString = qopList.toString();
this.saslQop = saslQop;
}
/**
* Returns the realms serviced by this SASL host, used by DIGEST-MD5 and GSSAPI.
*
* @return The realms serviced by this SASL host, used by DIGEST-MD5 and GSSAPI.
*/
public List<String> getSaslRealms()
{
return saslRealms;
}
/**
* Sets the realms serviced by this SASL host, used by DIGEST-MD5 and GSSAPI.
*
* @org.apache.xbean.Property nestedType="java.lang.String"
*
* @param saslRealms The realms serviced by this SASL host, used by DIGEST-MD5 and GSSAPI.
*/
public void setSaslRealms( List<String> saslRealms )
{
this.saslRealms = saslRealms;
}
/**
* @org.apache.xbean.Map flat="true" dups="replace" keyName="mech-name"
*/
public Map<String, MechanismHandler> getSaslMechanismHandlers()
{
return saslMechanismHandlers;
}
public void setSaslMechanismHandlers( Map<String, MechanismHandler> saslMechanismHandlers )
{
this.saslMechanismHandlers = saslMechanismHandlers;
}
public MechanismHandler addSaslMechanismHandler( String mechanism, MechanismHandler handler )
{
return this.saslMechanismHandlers.put( mechanism, handler );
}
public MechanismHandler removeSaslMechanismHandler( String mechanism )
{
return this.saslMechanismHandlers.remove( mechanism );
}
public MechanismHandler getMechanismHandler( String mechanism )
{
return this.saslMechanismHandlers.get( mechanism );
}
public Set<String> getSupportedMechanisms()
{
return saslMechanismHandlers.keySet();
}
public void setDirectoryService( DirectoryService directoryService )
{
super.setDirectoryService( directoryService );
this.codecFactory = new LdapProtocolCodecFactory( directoryService );
}
public Set<String> getSupportedControls()
{
return supportedControls;
}
/**
* @org.apache.xbean.Property hidden="true"
*/
public void setSupportedControls( Set<String> supportedControls )
{
this.supportedControls = supportedControls;
}
public MessageHandler<InternalAbandonRequest> getAbandonHandler()
{
return abandonHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The AbandonRequest handler
*/
public void setAbandonHandler( LdapRequestHandler<InternalAbandonRequest> abandonHandler )
{
this.handler.removeReceivedMessageHandler( InternalAbandonRequest.class );
this.abandonHandler = abandonHandler;
this.abandonHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalAbandonRequest.class, this.abandonHandler );
}
public LdapRequestHandler<InternalAddRequest> getAddHandler()
{
return addHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The AddRequest handler
*/
public void setAddHandler( LdapRequestHandler<InternalAddRequest> addHandler )
{
this.handler.removeReceivedMessageHandler( InternalAddRequest.class );
this.addHandler = addHandler;
this.addHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalAddRequest.class, this.addHandler );
}
public LdapRequestHandler<InternalBindRequest> getBindHandler()
{
return bindHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The BindRequest handler
*/
public void setBindHandler( LdapRequestHandler<InternalBindRequest> bindHandler )
{
this.bindHandler = bindHandler;
this.bindHandler.setLdapServer( this );
handler.removeReceivedMessageHandler( InternalBindRequest.class );
handler.addReceivedMessageHandler( InternalBindRequest.class, this.bindHandler );
}
public LdapRequestHandler<InternalCompareRequest> getCompareHandler()
{
return compareHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The CompareRequest handler
*/
public void setCompareHandler( LdapRequestHandler<InternalCompareRequest> compareHandler )
{
this.handler.removeReceivedMessageHandler( InternalCompareRequest.class );
this.compareHandler = compareHandler;
this.compareHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalCompareRequest.class, this.compareHandler );
}
public LdapRequestHandler<InternalDeleteRequest> getDeleteHandler()
{
return deleteHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The DeleteRequest handler
*/
public void setDeleteHandler( LdapRequestHandler<InternalDeleteRequest> deleteHandler )
{
this.handler.removeReceivedMessageHandler( InternalDeleteRequest.class );
this.deleteHandler = deleteHandler;
this.deleteHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalDeleteRequest.class, this.deleteHandler );
}
public LdapRequestHandler<InternalExtendedRequest> getExtendedHandler()
{
return extendedHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The ExtendedRequest handler
*/
public void setExtendedHandler( LdapRequestHandler<InternalExtendedRequest> extendedHandler )
{
this.handler.removeReceivedMessageHandler( InternalExtendedRequest.class );
this.extendedHandler = extendedHandler;
this.extendedHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalExtendedRequest.class, this.extendedHandler );
}
public LdapRequestHandler<InternalModifyRequest> getModifyHandler()
{
return modifyHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The ModifyRequest handler
*/
public void setModifyHandler( LdapRequestHandler<InternalModifyRequest> modifyHandler )
{
this.handler.removeReceivedMessageHandler( InternalModifyRequest.class );
this.modifyHandler = modifyHandler;
this.modifyHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalModifyRequest.class, this.modifyHandler );
}
public LdapRequestHandler<InternalModifyDnRequest> getModifyDnHandler()
{
return modifyDnHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The ModifyDNRequest handler
*/
public void setModifyDnHandler( LdapRequestHandler<InternalModifyDnRequest> modifyDnHandler )
{
this.handler.removeReceivedMessageHandler( InternalModifyDnRequest.class );
this.modifyDnHandler = modifyDnHandler;
this.modifyDnHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalModifyDnRequest.class, this.modifyDnHandler );
}
public LdapRequestHandler<InternalSearchRequest> getSearchHandler()
{
return searchHandler;
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The SearchRequest handler
*/
public void setSearchHandler( LdapRequestHandler<InternalSearchRequest> searchHandler )
{
this.handler.removeReceivedMessageHandler( InternalSearchRequest.class );
this.searchHandler = searchHandler;
this.searchHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalSearchRequest.class, this.searchHandler );
}
public LdapRequestHandler<InternalUnbindRequest> getUnbindHandler()
{
return unbindHandler;
}
/**
* @return The underlying TCP transport port, or -1 if no transport has been
* initialized
*/
public int getPort()
{
return getTcpTransport() == null ? -1 : getTcpTransport().getPort();
}
/**
* @org.apache.xbean.Property hidden="true"
* @param abandonHandler The UnbindRequest handler
*/
public void setUnbindHandler( LdapRequestHandler<InternalUnbindRequest> unbindHandler )
{
this.handler.removeReceivedMessageHandler( InternalUnbindRequest.class );
this.unbindHandler = unbindHandler;
this.unbindHandler.setLdapServer( this );
this.handler.addReceivedMessageHandler( InternalUnbindRequest.class, this.unbindHandler );
}
public boolean isStarted()
{
return started;
}
/**
* @org.apache.xbean.Property hidden="true"
*/
public void setStarted( boolean started )
{
this.started = started;
}
/**
* @return The keystore path
*/
public String getKeystoreFile()
{
return keystoreFile;
}
/**
* Set the external keystore path
* @param keystoreFile The external keystore path
*/
public void setKeystoreFile( String keystoreFile )
{
this.keystoreFile = keystoreFile;
}
/**
* @return The certificate passord
*/
public String getCertificatePassword()
{
return certificatePassword;
}
/**
* Set the certificate passord.
* @param certificatePassword the certificate passord
*/
public void setCertificatePassword( String certificatePassword )
{
this.certificatePassword = certificatePassword;
}
/**
* @param replicationSystem the replicationSystem to set
*/
public void setReplicationSystem( ReplicationSystem replicationSystem )
{
this.replicationSystem = replicationSystem;
}
/**
* @return the replicationSystem
*/
public ReplicationSystem getReplicationSystem()
{
return replicationSystem;
}
}
| true | true | public void start() throws Exception
{
if ( ! isEnabled() )
{
return;
}
IoFilterChainBuilder chain;
if ( isEnableLdaps() )
{
KeyStore keyStore = null;
if ( StringTools.isEmpty( keystoreFile ) )
{
Provider provider = Security.getProvider( "SUN" );
LOG.debug( "provider = {}", provider );
CoreKeyStoreSpi coreKeyStoreSpi = new CoreKeyStoreSpi( getDirectoryService() );
keyStore = new KeyStore( coreKeyStoreSpi, provider, "JKS" ) {};
try
{
keyStore.load( null, null );
}
catch ( Exception e )
{
// nothing really happens with this keystore
}
}
else
{
keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
FileInputStream fis = new FileInputStream( keystoreFile );
keyStore.load( fis, null );
}
chain = LdapsInitializer.init( keyStore, certificatePassword );
}
else
{
chain = new DefaultIoFilterChainBuilder();
}
// Inject the codec into the chain
((DefaultIoFilterChainBuilder)chain).addLast( "codec",
new ProtocolCodecFilter( this.getProtocolCodecFactory() ) );
// Now inject an ExecutorFilter for the write operations
// We use the same number of thread than the number of IoProcessor
// (NOTE : this has to be double checked)
((DefaultIoFilterChainBuilder)chain).addLast( "executor",
new ExecutorFilter( new OrderedThreadPoolExecutor( getTcpTransport().getNbThreads() ),
IoEventType.WRITE ) );
/*
* The server is now initialized, we can
* install the default requests handlers, which need
* access to the DirectoryServer instance.
*/
installDefaultHandlers();
startNetwork(
getTcpTransport().getAddress(),
getTcpTransport().getPort(),
getTcpTransport().getBackLog(), chain );
started = true;
if ( isEnableLdaps() )
{
LOG.info( "Ldaps service started." );
System.out.println( "Ldaps service started." );
}
else
{
LOG.info( "Ldap service started." );
System.out.println( "Ldap service started." );
}
}
| public void start() throws Exception
{
if ( ! isEnabled() )
{
return;
}
IoFilterChainBuilder chain;
if ( isEnableLdaps() )
{
KeyStore keyStore = null;
if ( StringTools.isEmpty( keystoreFile ) )
{
Provider provider = Security.getProvider( "SUN" );
LOG.debug( "provider = {}", provider );
CoreKeyStoreSpi coreKeyStoreSpi = new CoreKeyStoreSpi( getDirectoryService() );
keyStore = new KeyStore( coreKeyStoreSpi, provider, "JKS" ) {};
try
{
keyStore.load( null, null );
}
catch ( Exception e )
{
// nothing really happens with this keystore
}
}
else
{
keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
FileInputStream fis = new FileInputStream( keystoreFile );
keyStore.load( fis, null );
}
chain = LdapsInitializer.init( keyStore, certificatePassword );
}
else
{
chain = new DefaultIoFilterChainBuilder();
}
// Inject the codec into the chain
((DefaultIoFilterChainBuilder)chain).addLast( "codec",
new ProtocolCodecFilter( this.getProtocolCodecFactory() ) );
// Now inject an ExecutorFilter for the write operations
// We use the same number of thread than the number of IoProcessor
// (NOTE : this has to be double checked)
((DefaultIoFilterChainBuilder)chain).addLast( "executor",
new ExecutorFilter(
new OrderedThreadPoolExecutor( getTcpTransport().getNbThreads() ) ) );
/*
* The server is now initialized, we can
* install the default requests handlers, which need
* access to the DirectoryServer instance.
*/
installDefaultHandlers();
startNetwork(
getTcpTransport().getAddress(),
getTcpTransport().getPort(),
getTcpTransport().getBackLog(), chain );
started = true;
if ( isEnableLdaps() )
{
LOG.info( "Ldaps service started." );
System.out.println( "Ldaps service started." );
}
else
{
LOG.info( "Ldap service started." );
System.out.println( "Ldap service started." );
}
}
|
diff --git a/src/com/android/contacts/model/ContactLoader.java b/src/com/android/contacts/model/ContactLoader.java
index 4c0e70aca..8583f147f 100644
--- a/src/com/android/contacts/model/ContactLoader.java
+++ b/src/com/android/contacts/model/ContactLoader.java
@@ -1,954 +1,955 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.contacts.model;
import android.content.AsyncTaskLoader;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;
import com.android.contacts.GroupMetaData;
import com.android.contacts.common.GeoUtil;
import com.android.contacts.common.model.AccountTypeManager;
import com.android.contacts.common.model.account.AccountType;
import com.android.contacts.common.model.account.AccountTypeWithDataSet;
import com.android.contacts.common.util.Constants;
import com.android.contacts.common.util.UriUtils;
import com.android.contacts.model.dataitem.DataItem;
import com.android.contacts.model.dataitem.PhoneDataItem;
import com.android.contacts.model.dataitem.PhotoDataItem;
import com.android.contacts.util.ContactLoaderUtils;
import com.android.contacts.util.DataStatus;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Loads a single Contact and all it constituent RawContacts.
*/
public class ContactLoader extends AsyncTaskLoader<Contact> {
private static final String TAG = ContactLoader.class.getSimpleName();
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
/** A short-lived cache that can be set by {@link #cacheResult()} */
private static Contact sCachedResult = null;
private final Uri mRequestedUri;
private Uri mLookupUri;
private boolean mLoadGroupMetaData;
private boolean mLoadInvitableAccountTypes;
private boolean mPostViewNotification;
private boolean mComputeFormattedPhoneNumber;
private Contact mContact;
private ForceLoadContentObserver mObserver;
private final Set<Long> mNotifiedRawContactIds = Sets.newHashSet();
public ContactLoader(Context context, Uri lookupUri, boolean postViewNotification) {
this(context, lookupUri, false, false, postViewNotification, false);
}
public ContactLoader(Context context, Uri lookupUri, boolean loadGroupMetaData,
boolean loadInvitableAccountTypes,
boolean postViewNotification, boolean computeFormattedPhoneNumber) {
super(context);
mLookupUri = lookupUri;
mRequestedUri = lookupUri;
mLoadGroupMetaData = loadGroupMetaData;
mLoadInvitableAccountTypes = loadInvitableAccountTypes;
mPostViewNotification = postViewNotification;
mComputeFormattedPhoneNumber = computeFormattedPhoneNumber;
}
/**
* Projection used for the query that loads all data for the entire contact (except for
* social stream items).
*/
private static class ContactQuery {
static final String[] COLUMNS = new String[] {
Contacts.NAME_RAW_CONTACT_ID,
Contacts.DISPLAY_NAME_SOURCE,
Contacts.LOOKUP_KEY,
Contacts.DISPLAY_NAME,
Contacts.DISPLAY_NAME_ALTERNATIVE,
Contacts.PHONETIC_NAME,
Contacts.PHOTO_ID,
Contacts.STARRED,
Contacts.CONTACT_PRESENCE,
Contacts.CONTACT_STATUS,
Contacts.CONTACT_STATUS_TIMESTAMP,
Contacts.CONTACT_STATUS_RES_PACKAGE,
Contacts.CONTACT_STATUS_LABEL,
Contacts.Entity.CONTACT_ID,
Contacts.Entity.RAW_CONTACT_ID,
RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE,
RawContacts.DATA_SET,
RawContacts.ACCOUNT_TYPE_AND_DATA_SET,
RawContacts.DIRTY,
RawContacts.VERSION,
RawContacts.SOURCE_ID,
RawContacts.SYNC1,
RawContacts.SYNC2,
RawContacts.SYNC3,
RawContacts.SYNC4,
RawContacts.DELETED,
RawContacts.NAME_VERIFIED,
Contacts.Entity.DATA_ID,
Data.DATA1,
Data.DATA2,
Data.DATA3,
Data.DATA4,
Data.DATA5,
Data.DATA6,
Data.DATA7,
Data.DATA8,
Data.DATA9,
Data.DATA10,
Data.DATA11,
Data.DATA12,
Data.DATA13,
Data.DATA14,
Data.DATA15,
Data.SYNC1,
Data.SYNC2,
Data.SYNC3,
Data.SYNC4,
Data.DATA_VERSION,
Data.IS_PRIMARY,
Data.IS_SUPER_PRIMARY,
Data.MIMETYPE,
Data.RES_PACKAGE,
GroupMembership.GROUP_SOURCE_ID,
Data.PRESENCE,
Data.CHAT_CAPABILITY,
Data.STATUS,
Data.STATUS_RES_PACKAGE,
Data.STATUS_ICON,
Data.STATUS_LABEL,
Data.STATUS_TIMESTAMP,
Contacts.PHOTO_URI,
Contacts.SEND_TO_VOICEMAIL,
Contacts.CUSTOM_RINGTONE,
Contacts.IS_USER_PROFILE,
};
public static final int NAME_RAW_CONTACT_ID = 0;
public static final int DISPLAY_NAME_SOURCE = 1;
public static final int LOOKUP_KEY = 2;
public static final int DISPLAY_NAME = 3;
public static final int ALT_DISPLAY_NAME = 4;
public static final int PHONETIC_NAME = 5;
public static final int PHOTO_ID = 6;
public static final int STARRED = 7;
public static final int CONTACT_PRESENCE = 8;
public static final int CONTACT_STATUS = 9;
public static final int CONTACT_STATUS_TIMESTAMP = 10;
public static final int CONTACT_STATUS_RES_PACKAGE = 11;
public static final int CONTACT_STATUS_LABEL = 12;
public static final int CONTACT_ID = 13;
public static final int RAW_CONTACT_ID = 14;
public static final int ACCOUNT_NAME = 15;
public static final int ACCOUNT_TYPE = 16;
public static final int DATA_SET = 17;
public static final int ACCOUNT_TYPE_AND_DATA_SET = 18;
public static final int DIRTY = 19;
public static final int VERSION = 20;
public static final int SOURCE_ID = 21;
public static final int SYNC1 = 22;
public static final int SYNC2 = 23;
public static final int SYNC3 = 24;
public static final int SYNC4 = 25;
public static final int DELETED = 26;
public static final int NAME_VERIFIED = 27;
public static final int DATA_ID = 28;
public static final int DATA1 = 29;
public static final int DATA2 = 30;
public static final int DATA3 = 31;
public static final int DATA4 = 32;
public static final int DATA5 = 33;
public static final int DATA6 = 34;
public static final int DATA7 = 35;
public static final int DATA8 = 36;
public static final int DATA9 = 37;
public static final int DATA10 = 38;
public static final int DATA11 = 39;
public static final int DATA12 = 40;
public static final int DATA13 = 41;
public static final int DATA14 = 42;
public static final int DATA15 = 43;
public static final int DATA_SYNC1 = 44;
public static final int DATA_SYNC2 = 45;
public static final int DATA_SYNC3 = 46;
public static final int DATA_SYNC4 = 47;
public static final int DATA_VERSION = 48;
public static final int IS_PRIMARY = 49;
public static final int IS_SUPERPRIMARY = 50;
public static final int MIMETYPE = 51;
public static final int RES_PACKAGE = 52;
public static final int GROUP_SOURCE_ID = 53;
public static final int PRESENCE = 54;
public static final int CHAT_CAPABILITY = 55;
public static final int STATUS = 56;
public static final int STATUS_RES_PACKAGE = 57;
public static final int STATUS_ICON = 58;
public static final int STATUS_LABEL = 59;
public static final int STATUS_TIMESTAMP = 60;
public static final int PHOTO_URI = 61;
public static final int SEND_TO_VOICEMAIL = 62;
public static final int CUSTOM_RINGTONE = 63;
public static final int IS_USER_PROFILE = 64;
}
/**
* Projection used for the query that loads all data for the entire contact.
*/
private static class DirectoryQuery {
static final String[] COLUMNS = new String[] {
Directory.DISPLAY_NAME,
Directory.PACKAGE_NAME,
Directory.TYPE_RESOURCE_ID,
Directory.ACCOUNT_TYPE,
Directory.ACCOUNT_NAME,
Directory.EXPORT_SUPPORT,
};
public static final int DISPLAY_NAME = 0;
public static final int PACKAGE_NAME = 1;
public static final int TYPE_RESOURCE_ID = 2;
public static final int ACCOUNT_TYPE = 3;
public static final int ACCOUNT_NAME = 4;
public static final int EXPORT_SUPPORT = 5;
}
private static class GroupQuery {
static final String[] COLUMNS = new String[] {
Groups.ACCOUNT_NAME,
Groups.ACCOUNT_TYPE,
Groups.DATA_SET,
Groups.ACCOUNT_TYPE_AND_DATA_SET,
Groups._ID,
Groups.TITLE,
Groups.AUTO_ADD,
Groups.FAVORITES,
};
public static final int ACCOUNT_NAME = 0;
public static final int ACCOUNT_TYPE = 1;
public static final int DATA_SET = 2;
public static final int ACCOUNT_TYPE_AND_DATA_SET = 3;
public static final int ID = 4;
public static final int TITLE = 5;
public static final int AUTO_ADD = 6;
public static final int FAVORITES = 7;
}
@Override
public Contact loadInBackground() {
try {
final ContentResolver resolver = getContext().getContentResolver();
final Uri uriCurrentFormat = ContactLoaderUtils.ensureIsContactUri(
resolver, mLookupUri);
final Contact cachedResult = sCachedResult;
sCachedResult = null;
// Is this the same Uri as what we had before already? In that case, reuse that result
final Contact result;
final boolean resultIsCached;
if (cachedResult != null &&
UriUtils.areEqual(cachedResult.getLookupUri(), mLookupUri)) {
// We are using a cached result from earlier. Below, we should make sure
// we are not doing any more network or disc accesses
result = new Contact(mRequestedUri, cachedResult);
resultIsCached = true;
} else {
if (uriCurrentFormat.getLastPathSegment().equals(Constants.LOOKUP_URI_ENCODED)) {
result = loadEncodedContactEntity(uriCurrentFormat);
} else {
result = loadContactEntity(resolver, uriCurrentFormat);
}
resultIsCached = false;
}
if (result.isLoaded()) {
if (result.isDirectoryEntry()) {
if (!resultIsCached) {
loadDirectoryMetaData(result);
}
} else if (mLoadGroupMetaData) {
if (result.getGroupMetaData() == null) {
loadGroupMetaData(result);
}
}
if (mComputeFormattedPhoneNumber) {
computeFormattedPhoneNumbers(result);
}
if (!resultIsCached) loadPhotoBinaryData(result);
// Note ME profile should never have "Add connection"
if (mLoadInvitableAccountTypes && result.getInvitableAccountTypes() == null) {
loadInvitableAccountTypes(result);
}
}
return result;
} catch (Exception e) {
Log.e(TAG, "Error loading the contact: " + mLookupUri, e);
return Contact.forError(mRequestedUri, e);
}
}
private Contact loadEncodedContactEntity(Uri uri) throws JSONException {
final String jsonString = uri.getQueryParameter(Constants.LOOKUP_URI_JSON);
final JSONObject json = new JSONObject(jsonString);
final long directoryId =
Long.valueOf(uri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY));
final String displayName = json.getString(Contacts.DISPLAY_NAME);
final String altDisplayName = json.optString(
Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
final int displayNameSource = json.getInt(Contacts.DISPLAY_NAME_SOURCE);
final String photoUri = json.optString(Contacts.PHOTO_URI, null);
final Contact contact = new Contact(
uri, uri,
mLookupUri,
directoryId,
null /* lookupKey */,
-1 /* id */,
-1 /* nameRawContactId */,
displayNameSource,
-1 /* photoId */,
photoUri,
displayName,
altDisplayName,
null /* phoneticName */,
false /* starred */,
null /* presence */,
false /* sendToVoicemail */,
null /* customRingtone */,
false /* isUserProfile */);
contact.setStatuses(new ImmutableMap.Builder<Long, DataStatus>().build());
final String accountName = json.optString(RawContacts.ACCOUNT_NAME, null);
final String directoryName = uri.getQueryParameter(Directory.DISPLAY_NAME);
if (accountName != null) {
final String accountType = json.getString(RawContacts.ACCOUNT_TYPE);
contact.setDirectoryMetaData(directoryName, null, accountName, accountType,
- Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY);
+ json.optInt(Directory.EXPORT_SUPPORT,
+ Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY));
} else {
contact.setDirectoryMetaData(directoryName, null, null, null,
- Directory.EXPORT_SUPPORT_ANY_ACCOUNT);
+ json.optInt(Directory.EXPORT_SUPPORT, Directory.EXPORT_SUPPORT_ANY_ACCOUNT));
}
final ContentValues values = new ContentValues();
values.put(Data._ID, -1);
values.put(Data.CONTACT_ID, -1);
final RawContact rawContact = new RawContact(values);
final JSONObject items = json.getJSONObject(Contacts.CONTENT_ITEM_TYPE);
final Iterator keys = items.keys();
while (keys.hasNext()) {
final String mimetype = (String) keys.next();
final JSONObject item = items.getJSONObject(mimetype);
final ContentValues itemValues = new ContentValues();
itemValues.put(Data.MIMETYPE, mimetype);
itemValues.put(Data._ID, -1);
final Iterator iterator = item.keys();
while (iterator.hasNext()) {
String name = (String) iterator.next();
final Object o = item.get(name);
if (o instanceof String) {
itemValues.put(name, (String) o);
} else if (o instanceof Integer) {
itemValues.put(name, (Integer) o);
}
}
rawContact.addDataItemValues(itemValues);
}
contact.setRawContacts(new ImmutableList.Builder<RawContact>()
.add(rawContact)
.build());
return contact;
}
private Contact loadContactEntity(ContentResolver resolver, Uri contactUri) {
Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY);
Cursor cursor = resolver.query(entityUri, ContactQuery.COLUMNS, null, null,
Contacts.Entity.RAW_CONTACT_ID);
if (cursor == null) {
Log.e(TAG, "No cursor returned in loadContactEntity");
return Contact.forNotFound(mRequestedUri);
}
try {
if (!cursor.moveToFirst()) {
cursor.close();
return Contact.forNotFound(mRequestedUri);
}
// Create the loaded contact starting with the header data.
Contact contact = loadContactHeaderData(cursor, contactUri);
// Fill in the raw contacts, which is wrapped in an Entity and any
// status data. Initially, result has empty entities and statuses.
long currentRawContactId = -1;
RawContact rawContact = null;
ImmutableList.Builder<RawContact> rawContactsBuilder =
new ImmutableList.Builder<RawContact>();
ImmutableMap.Builder<Long, DataStatus> statusesBuilder =
new ImmutableMap.Builder<Long, DataStatus>();
do {
long rawContactId = cursor.getLong(ContactQuery.RAW_CONTACT_ID);
if (rawContactId != currentRawContactId) {
// First time to see this raw contact id, so create a new entity, and
// add it to the result's entities.
currentRawContactId = rawContactId;
rawContact = new RawContact(loadRawContactValues(cursor));
rawContactsBuilder.add(rawContact);
}
if (!cursor.isNull(ContactQuery.DATA_ID)) {
ContentValues data = loadDataValues(cursor);
rawContact.addDataItemValues(data);
if (!cursor.isNull(ContactQuery.PRESENCE)
|| !cursor.isNull(ContactQuery.STATUS)) {
final DataStatus status = new DataStatus(cursor);
final long dataId = cursor.getLong(ContactQuery.DATA_ID);
statusesBuilder.put(dataId, status);
}
}
} while (cursor.moveToNext());
contact.setRawContacts(rawContactsBuilder.build());
contact.setStatuses(statusesBuilder.build());
return contact;
} finally {
cursor.close();
}
}
/**
* Looks for the photo data item in entities. If found, creates a new Bitmap instance. If
* not found, returns null
*/
private void loadPhotoBinaryData(Contact contactData) {
// If we have a photo URI, try loading that first.
String photoUri = contactData.getPhotoUri();
if (photoUri != null) {
try {
final InputStream inputStream;
final AssetFileDescriptor fd;
final Uri uri = Uri.parse(photoUri);
final String scheme = uri.getScheme();
if ("http".equals(scheme) || "https".equals(scheme)) {
// Support HTTP urls that might come from extended directories
inputStream = new URL(photoUri).openStream();
fd = null;
} else {
fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
inputStream = fd.createInputStream();
}
byte[] buffer = new byte[16 * 1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
int size;
while ((size = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, size);
}
contactData.setPhotoBinaryData(baos.toByteArray());
} finally {
inputStream.close();
if (fd != null) {
fd.close();
}
}
return;
} catch (IOException ioe) {
// Just fall back to the case below.
}
}
// If we couldn't load from a file, fall back to the data blob.
final long photoId = contactData.getPhotoId();
if (photoId <= 0) {
// No photo ID
return;
}
for (RawContact rawContact : contactData.getRawContacts()) {
for (DataItem dataItem : rawContact.getDataItems()) {
if (dataItem.getId() == photoId) {
if (!(dataItem instanceof PhotoDataItem)) {
break;
}
final PhotoDataItem photo = (PhotoDataItem) dataItem;
contactData.setPhotoBinaryData(photo.getPhoto());
break;
}
}
}
}
/**
* Sets the "invitable" account types to {@link Contact#mInvitableAccountTypes}.
*/
private void loadInvitableAccountTypes(Contact contactData) {
final ImmutableList.Builder<AccountType> resultListBuilder =
new ImmutableList.Builder<AccountType>();
if (!contactData.isUserProfile()) {
Map<AccountTypeWithDataSet, AccountType> invitables =
AccountTypeManager.getInstance(getContext()).getUsableInvitableAccountTypes();
if (!invitables.isEmpty()) {
final Map<AccountTypeWithDataSet, AccountType> resultMap =
Maps.newHashMap(invitables);
// Remove the ones that already have a raw contact in the current contact
for (RawContact rawContact : contactData.getRawContacts()) {
final AccountTypeWithDataSet type = AccountTypeWithDataSet.get(
rawContact.getAccountTypeString(),
rawContact.getDataSet());
resultMap.remove(type);
}
resultListBuilder.addAll(resultMap.values());
}
}
// Set to mInvitableAccountTypes
contactData.setInvitableAccountTypes(resultListBuilder.build());
}
/**
* Extracts Contact level columns from the cursor.
*/
private Contact loadContactHeaderData(final Cursor cursor, Uri contactUri) {
final String directoryParameter =
contactUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
final long directoryId = directoryParameter == null
? Directory.DEFAULT
: Long.parseLong(directoryParameter);
final long contactId = cursor.getLong(ContactQuery.CONTACT_ID);
final String lookupKey = cursor.getString(ContactQuery.LOOKUP_KEY);
final long nameRawContactId = cursor.getLong(ContactQuery.NAME_RAW_CONTACT_ID);
final int displayNameSource = cursor.getInt(ContactQuery.DISPLAY_NAME_SOURCE);
final String displayName = cursor.getString(ContactQuery.DISPLAY_NAME);
final String altDisplayName = cursor.getString(ContactQuery.ALT_DISPLAY_NAME);
final String phoneticName = cursor.getString(ContactQuery.PHONETIC_NAME);
final long photoId = cursor.getLong(ContactQuery.PHOTO_ID);
final String photoUri = cursor.getString(ContactQuery.PHOTO_URI);
final boolean starred = cursor.getInt(ContactQuery.STARRED) != 0;
final Integer presence = cursor.isNull(ContactQuery.CONTACT_PRESENCE)
? null
: cursor.getInt(ContactQuery.CONTACT_PRESENCE);
final boolean sendToVoicemail = cursor.getInt(ContactQuery.SEND_TO_VOICEMAIL) == 1;
final String customRingtone = cursor.getString(ContactQuery.CUSTOM_RINGTONE);
final boolean isUserProfile = cursor.getInt(ContactQuery.IS_USER_PROFILE) == 1;
Uri lookupUri;
if (directoryId == Directory.DEFAULT || directoryId == Directory.LOCAL_INVISIBLE) {
lookupUri = ContentUris.withAppendedId(
Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId);
} else {
lookupUri = contactUri;
}
return new Contact(mRequestedUri, contactUri, lookupUri, directoryId, lookupKey,
contactId, nameRawContactId, displayNameSource, photoId, photoUri, displayName,
altDisplayName, phoneticName, starred, presence, sendToVoicemail,
customRingtone, isUserProfile);
}
/**
* Extracts RawContact level columns from the cursor.
*/
private ContentValues loadRawContactValues(Cursor cursor) {
ContentValues cv = new ContentValues();
cv.put(RawContacts._ID, cursor.getLong(ContactQuery.RAW_CONTACT_ID));
cursorColumnToContentValues(cursor, cv, ContactQuery.ACCOUNT_NAME);
cursorColumnToContentValues(cursor, cv, ContactQuery.ACCOUNT_TYPE);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_SET);
cursorColumnToContentValues(cursor, cv, ContactQuery.ACCOUNT_TYPE_AND_DATA_SET);
cursorColumnToContentValues(cursor, cv, ContactQuery.DIRTY);
cursorColumnToContentValues(cursor, cv, ContactQuery.VERSION);
cursorColumnToContentValues(cursor, cv, ContactQuery.SOURCE_ID);
cursorColumnToContentValues(cursor, cv, ContactQuery.SYNC1);
cursorColumnToContentValues(cursor, cv, ContactQuery.SYNC2);
cursorColumnToContentValues(cursor, cv, ContactQuery.SYNC3);
cursorColumnToContentValues(cursor, cv, ContactQuery.SYNC4);
cursorColumnToContentValues(cursor, cv, ContactQuery.DELETED);
cursorColumnToContentValues(cursor, cv, ContactQuery.CONTACT_ID);
cursorColumnToContentValues(cursor, cv, ContactQuery.STARRED);
cursorColumnToContentValues(cursor, cv, ContactQuery.NAME_VERIFIED);
return cv;
}
/**
* Extracts Data level columns from the cursor.
*/
private ContentValues loadDataValues(Cursor cursor) {
ContentValues cv = new ContentValues();
cv.put(Data._ID, cursor.getLong(ContactQuery.DATA_ID));
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA1);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA2);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA3);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA4);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA5);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA6);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA7);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA8);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA9);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA10);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA11);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA12);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA13);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA14);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA15);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_SYNC1);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_SYNC2);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_SYNC3);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_SYNC4);
cursorColumnToContentValues(cursor, cv, ContactQuery.DATA_VERSION);
cursorColumnToContentValues(cursor, cv, ContactQuery.IS_PRIMARY);
cursorColumnToContentValues(cursor, cv, ContactQuery.IS_SUPERPRIMARY);
cursorColumnToContentValues(cursor, cv, ContactQuery.MIMETYPE);
cursorColumnToContentValues(cursor, cv, ContactQuery.RES_PACKAGE);
cursorColumnToContentValues(cursor, cv, ContactQuery.GROUP_SOURCE_ID);
cursorColumnToContentValues(cursor, cv, ContactQuery.CHAT_CAPABILITY);
return cv;
}
private void cursorColumnToContentValues(
Cursor cursor, ContentValues values, int index) {
switch (cursor.getType(index)) {
case Cursor.FIELD_TYPE_NULL:
// don't put anything in the content values
break;
case Cursor.FIELD_TYPE_INTEGER:
values.put(ContactQuery.COLUMNS[index], cursor.getLong(index));
break;
case Cursor.FIELD_TYPE_STRING:
values.put(ContactQuery.COLUMNS[index], cursor.getString(index));
break;
case Cursor.FIELD_TYPE_BLOB:
values.put(ContactQuery.COLUMNS[index], cursor.getBlob(index));
break;
default:
throw new IllegalStateException("Invalid or unhandled data type");
}
}
private void loadDirectoryMetaData(Contact result) {
long directoryId = result.getDirectoryId();
Cursor cursor = getContext().getContentResolver().query(
ContentUris.withAppendedId(Directory.CONTENT_URI, directoryId),
DirectoryQuery.COLUMNS, null, null, null);
if (cursor == null) {
return;
}
try {
if (cursor.moveToFirst()) {
final String displayName = cursor.getString(DirectoryQuery.DISPLAY_NAME);
final String packageName = cursor.getString(DirectoryQuery.PACKAGE_NAME);
final int typeResourceId = cursor.getInt(DirectoryQuery.TYPE_RESOURCE_ID);
final String accountType = cursor.getString(DirectoryQuery.ACCOUNT_TYPE);
final String accountName = cursor.getString(DirectoryQuery.ACCOUNT_NAME);
final int exportSupport = cursor.getInt(DirectoryQuery.EXPORT_SUPPORT);
String directoryType = null;
if (!TextUtils.isEmpty(packageName)) {
PackageManager pm = getContext().getPackageManager();
try {
Resources resources = pm.getResourcesForApplication(packageName);
directoryType = resources.getString(typeResourceId);
} catch (NameNotFoundException e) {
Log.w(TAG, "Contact directory resource not found: "
+ packageName + "." + typeResourceId);
}
}
result.setDirectoryMetaData(
displayName, directoryType, accountType, accountName, exportSupport);
}
} finally {
cursor.close();
}
}
/**
* Loads groups meta-data for all groups associated with all constituent raw contacts'
* accounts.
*/
private void loadGroupMetaData(Contact result) {
StringBuilder selection = new StringBuilder();
ArrayList<String> selectionArgs = new ArrayList<String>();
for (RawContact rawContact : result.getRawContacts()) {
final String accountName = rawContact.getAccountName();
final String accountType = rawContact.getAccountTypeString();
final String dataSet = rawContact.getDataSet();
if (accountName != null && accountType != null) {
if (selection.length() != 0) {
selection.append(" OR ");
}
selection.append(
"(" + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?");
selectionArgs.add(accountName);
selectionArgs.add(accountType);
if (dataSet != null) {
selection.append(" AND " + Groups.DATA_SET + "=?");
selectionArgs.add(dataSet);
} else {
selection.append(" AND " + Groups.DATA_SET + " IS NULL");
}
selection.append(")");
}
}
final ImmutableList.Builder<GroupMetaData> groupListBuilder =
new ImmutableList.Builder<GroupMetaData>();
final Cursor cursor = getContext().getContentResolver().query(Groups.CONTENT_URI,
GroupQuery.COLUMNS, selection.toString(), selectionArgs.toArray(new String[0]),
null);
try {
while (cursor.moveToNext()) {
final String accountName = cursor.getString(GroupQuery.ACCOUNT_NAME);
final String accountType = cursor.getString(GroupQuery.ACCOUNT_TYPE);
final String dataSet = cursor.getString(GroupQuery.DATA_SET);
final long groupId = cursor.getLong(GroupQuery.ID);
final String title = cursor.getString(GroupQuery.TITLE);
final boolean defaultGroup = cursor.isNull(GroupQuery.AUTO_ADD)
? false
: cursor.getInt(GroupQuery.AUTO_ADD) != 0;
final boolean favorites = cursor.isNull(GroupQuery.FAVORITES)
? false
: cursor.getInt(GroupQuery.FAVORITES) != 0;
groupListBuilder.add(new GroupMetaData(
accountName, accountType, dataSet, groupId, title, defaultGroup,
favorites));
}
} finally {
cursor.close();
}
result.setGroupMetaData(groupListBuilder.build());
}
/**
* Iterates over all data items that represent phone numbers are tries to calculate a formatted
* number. This function can safely be called several times as no unformatted data is
* overwritten
*/
private void computeFormattedPhoneNumbers(Contact contactData) {
final String countryIso = GeoUtil.getCurrentCountryIso(getContext());
final ImmutableList<RawContact> rawContacts = contactData.getRawContacts();
final int rawContactCount = rawContacts.size();
for (int rawContactIndex = 0; rawContactIndex < rawContactCount; rawContactIndex++) {
final RawContact rawContact = rawContacts.get(rawContactIndex);
final List<DataItem> dataItems = rawContact.getDataItems();
final int dataCount = dataItems.size();
for (int dataIndex = 0; dataIndex < dataCount; dataIndex++) {
final DataItem dataItem = dataItems.get(dataIndex);
if (dataItem instanceof PhoneDataItem) {
final PhoneDataItem phoneDataItem = (PhoneDataItem) dataItem;
phoneDataItem.computeFormattedPhoneNumber(countryIso);
}
}
}
}
@Override
public void deliverResult(Contact result) {
unregisterObserver();
// The creator isn't interested in any further updates
if (isReset() || result == null) {
return;
}
mContact = result;
if (result.isLoaded()) {
mLookupUri = result.getLookupUri();
if (!result.isDirectoryEntry()) {
Log.i(TAG, "Registering content observer for " + mLookupUri);
if (mObserver == null) {
mObserver = new ForceLoadContentObserver();
}
getContext().getContentResolver().registerContentObserver(
mLookupUri, true, mObserver);
}
if (mPostViewNotification) {
// inform the source of the data that this contact is being looked at
postViewNotificationToSyncAdapter();
}
}
super.deliverResult(mContact);
}
/**
* Posts a message to the contributing sync adapters that have opted-in, notifying them
* that the contact has just been loaded
*/
private void postViewNotificationToSyncAdapter() {
Context context = getContext();
for (RawContact rawContact : mContact.getRawContacts()) {
final long rawContactId = rawContact.getId();
if (mNotifiedRawContactIds.contains(rawContactId)) {
continue; // Already notified for this raw contact.
}
mNotifiedRawContactIds.add(rawContactId);
final AccountType accountType = rawContact.getAccountType(context);
final String serviceName = accountType.getViewContactNotifyServiceClassName();
final String servicePackageName = accountType.getViewContactNotifyServicePackageName();
if (!TextUtils.isEmpty(serviceName) && !TextUtils.isEmpty(servicePackageName)) {
final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
final Intent intent = new Intent();
intent.setClassName(servicePackageName, serviceName);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, RawContacts.CONTENT_ITEM_TYPE);
try {
context.startService(intent);
} catch (Exception e) {
Log.e(TAG, "Error sending message to source-app", e);
}
}
}
}
private void unregisterObserver() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
}
/**
* Fully upgrades this ContactLoader to one with all lists fully loaded. When done, the
* new result will be delivered
*/
public void upgradeToFullContact() {
// Everything requested already? Nothing to do, so let's bail out
if (mLoadGroupMetaData && mLoadInvitableAccountTypes
&& mPostViewNotification && mComputeFormattedPhoneNumber) return;
mLoadGroupMetaData = true;
mLoadInvitableAccountTypes = true;
mPostViewNotification = true;
mComputeFormattedPhoneNumber = true;
// Cache the current result, so that we only load the "missing" parts of the contact.
cacheResult();
// Our load parameters have changed, so let's pretend the data has changed. Its the same
// thing, essentially.
onContentChanged();
}
public Uri getLookupUri() {
return mLookupUri;
}
@Override
protected void onStartLoading() {
if (mContact != null) {
deliverResult(mContact);
}
if (takeContentChanged() || mContact == null) {
forceLoad();
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
cancelLoad();
unregisterObserver();
mContact = null;
}
/**
* Caches the result, which is useful when we switch from activity to activity, using the same
* contact. If the next load is for a different contact, the cached result will be dropped
*/
public void cacheResult() {
if (mContact == null || !mContact.isLoaded()) {
sCachedResult = null;
} else {
sCachedResult = mContact;
}
}
}
| false | true | private Contact loadEncodedContactEntity(Uri uri) throws JSONException {
final String jsonString = uri.getQueryParameter(Constants.LOOKUP_URI_JSON);
final JSONObject json = new JSONObject(jsonString);
final long directoryId =
Long.valueOf(uri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY));
final String displayName = json.getString(Contacts.DISPLAY_NAME);
final String altDisplayName = json.optString(
Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
final int displayNameSource = json.getInt(Contacts.DISPLAY_NAME_SOURCE);
final String photoUri = json.optString(Contacts.PHOTO_URI, null);
final Contact contact = new Contact(
uri, uri,
mLookupUri,
directoryId,
null /* lookupKey */,
-1 /* id */,
-1 /* nameRawContactId */,
displayNameSource,
-1 /* photoId */,
photoUri,
displayName,
altDisplayName,
null /* phoneticName */,
false /* starred */,
null /* presence */,
false /* sendToVoicemail */,
null /* customRingtone */,
false /* isUserProfile */);
contact.setStatuses(new ImmutableMap.Builder<Long, DataStatus>().build());
final String accountName = json.optString(RawContacts.ACCOUNT_NAME, null);
final String directoryName = uri.getQueryParameter(Directory.DISPLAY_NAME);
if (accountName != null) {
final String accountType = json.getString(RawContacts.ACCOUNT_TYPE);
contact.setDirectoryMetaData(directoryName, null, accountName, accountType,
Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY);
} else {
contact.setDirectoryMetaData(directoryName, null, null, null,
Directory.EXPORT_SUPPORT_ANY_ACCOUNT);
}
final ContentValues values = new ContentValues();
values.put(Data._ID, -1);
values.put(Data.CONTACT_ID, -1);
final RawContact rawContact = new RawContact(values);
final JSONObject items = json.getJSONObject(Contacts.CONTENT_ITEM_TYPE);
final Iterator keys = items.keys();
while (keys.hasNext()) {
final String mimetype = (String) keys.next();
final JSONObject item = items.getJSONObject(mimetype);
final ContentValues itemValues = new ContentValues();
itemValues.put(Data.MIMETYPE, mimetype);
itemValues.put(Data._ID, -1);
final Iterator iterator = item.keys();
while (iterator.hasNext()) {
String name = (String) iterator.next();
final Object o = item.get(name);
if (o instanceof String) {
itemValues.put(name, (String) o);
} else if (o instanceof Integer) {
itemValues.put(name, (Integer) o);
}
}
rawContact.addDataItemValues(itemValues);
}
contact.setRawContacts(new ImmutableList.Builder<RawContact>()
.add(rawContact)
.build());
return contact;
}
| private Contact loadEncodedContactEntity(Uri uri) throws JSONException {
final String jsonString = uri.getQueryParameter(Constants.LOOKUP_URI_JSON);
final JSONObject json = new JSONObject(jsonString);
final long directoryId =
Long.valueOf(uri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY));
final String displayName = json.getString(Contacts.DISPLAY_NAME);
final String altDisplayName = json.optString(
Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
final int displayNameSource = json.getInt(Contacts.DISPLAY_NAME_SOURCE);
final String photoUri = json.optString(Contacts.PHOTO_URI, null);
final Contact contact = new Contact(
uri, uri,
mLookupUri,
directoryId,
null /* lookupKey */,
-1 /* id */,
-1 /* nameRawContactId */,
displayNameSource,
-1 /* photoId */,
photoUri,
displayName,
altDisplayName,
null /* phoneticName */,
false /* starred */,
null /* presence */,
false /* sendToVoicemail */,
null /* customRingtone */,
false /* isUserProfile */);
contact.setStatuses(new ImmutableMap.Builder<Long, DataStatus>().build());
final String accountName = json.optString(RawContacts.ACCOUNT_NAME, null);
final String directoryName = uri.getQueryParameter(Directory.DISPLAY_NAME);
if (accountName != null) {
final String accountType = json.getString(RawContacts.ACCOUNT_TYPE);
contact.setDirectoryMetaData(directoryName, null, accountName, accountType,
json.optInt(Directory.EXPORT_SUPPORT,
Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY));
} else {
contact.setDirectoryMetaData(directoryName, null, null, null,
json.optInt(Directory.EXPORT_SUPPORT, Directory.EXPORT_SUPPORT_ANY_ACCOUNT));
}
final ContentValues values = new ContentValues();
values.put(Data._ID, -1);
values.put(Data.CONTACT_ID, -1);
final RawContact rawContact = new RawContact(values);
final JSONObject items = json.getJSONObject(Contacts.CONTENT_ITEM_TYPE);
final Iterator keys = items.keys();
while (keys.hasNext()) {
final String mimetype = (String) keys.next();
final JSONObject item = items.getJSONObject(mimetype);
final ContentValues itemValues = new ContentValues();
itemValues.put(Data.MIMETYPE, mimetype);
itemValues.put(Data._ID, -1);
final Iterator iterator = item.keys();
while (iterator.hasNext()) {
String name = (String) iterator.next();
final Object o = item.get(name);
if (o instanceof String) {
itemValues.put(name, (String) o);
} else if (o instanceof Integer) {
itemValues.put(name, (Integer) o);
}
}
rawContact.addDataItemValues(itemValues);
}
contact.setRawContacts(new ImmutableList.Builder<RawContact>()
.add(rawContact)
.build());
return contact;
}
|
diff --git a/ginco-admin/src/main/java/fr/mcc/ginco/rest/services/ThesaurusConceptRestService.java b/ginco-admin/src/main/java/fr/mcc/ginco/rest/services/ThesaurusConceptRestService.java
index 45ef0cdd..1834f8ea 100644
--- a/ginco-admin/src/main/java/fr/mcc/ginco/rest/services/ThesaurusConceptRestService.java
+++ b/ginco-admin/src/main/java/fr/mcc/ginco/rest/services/ThesaurusConceptRestService.java
@@ -1,210 +1,211 @@
/**
* Copyright or © or Copr. Ministère Français chargé de la Culture
* et de la Communication (2013)
* <p/>
* contact.gincoculture_at_gouv.fr
* <p/>
* This software is a computer program whose purpose is to provide a thesaurus
* management solution.
* <p/>
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
* <p/>
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited liability.
* <p/>
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systemsand/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
* <p/>
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package fr.mcc.ginco.rest.services;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.jaxrs.ext.MessageContext;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import fr.mcc.ginco.IThesaurusConceptService;
import fr.mcc.ginco.IThesaurusService;
import fr.mcc.ginco.IThesaurusTermService;
import fr.mcc.ginco.beans.Thesaurus;
import fr.mcc.ginco.beans.ThesaurusConcept;
import fr.mcc.ginco.beans.ThesaurusTerm;
import fr.mcc.ginco.beans.users.IUser;
import fr.mcc.ginco.exceptions.BusinessException;
import fr.mcc.ginco.extjs.view.pojo.ThesaurusConceptView;
import fr.mcc.ginco.extjs.view.pojo.ThesaurusTermView;
import fr.mcc.ginco.extjs.view.utils.TermViewConverter;
import fr.mcc.ginco.log.Log;
import fr.mcc.ginco.users.SimpleUserImpl;
import fr.mcc.ginco.utils.DateUtil;
/**
* Thesaurus Concept REST service for all operation on a thesaurus' concepts
*
*/
@Service
@Path("/thesaurusconceptservice")
@Produces({ MediaType.APPLICATION_JSON })
public class ThesaurusConceptRestService {
@Context
private MessageContext context;
@Inject
@Named("thesaurusTermService")
private IThesaurusTermService thesaurusTermService;
@Inject
@Named("thesaurusService")
private IThesaurusService thesaurusService;
@Inject
@Named("thesaurusConceptService")
private IThesaurusConceptService thesaurusConceptService;
@Inject
@Named("termViewConverter")
private TermViewConverter termViewConverter;
@Log
private Logger logger;
/**
* Public method used to create or update a concept
* @throws BusinessException
*/
@POST
@Path("/updateConcept")
@Consumes({ MediaType.APPLICATION_JSON })
public ThesaurusConceptView updateConcept(ThesaurusConceptView thesaurusConceptViewJAXBElement) throws BusinessException {
ThesaurusConcept convertedConcept = convertConcept(thesaurusConceptViewJAXBElement);
List <ThesaurusTerm> terms = convertTermViewsInTerms(thesaurusConceptViewJAXBElement);
logger.info("Number of converted terms : " + terms.size());
List <ThesaurusTerm> preferedTerm = thesaurusTermService.getPreferedTerms(terms);
//Business rule : a concept must have at least 1 term
if (preferedTerm.size() == 0) {
throw new BusinessException("A concept must have a prefered term");
}
//Business rule : a concept mustn't have more than one prefered term
if (preferedTerm.size() > 1) {
throw new BusinessException("A concept must have at only one prefered term");
}
String principal = "unknown";
if (context != null) {
principal = context.getHttpServletRequest().getRemoteAddr();
}
IUser user = new SimpleUserImpl();
user.setName(principal);
//We save or update the concept
ThesaurusConcept returnConcept = null;
if (StringUtils.isEmpty(convertedConcept.getIdentifier())) {
logger.info("Creating a new concept in DB");
returnConcept = thesaurusConceptService.createThesaurusConcept(convertedConcept, user);
} else {
//Case of existing concept
logger.info("Updating an existing concept in DB");
returnConcept = thesaurusConceptService.updateThesaurusConcept(convertedConcept, user);
}
//We save or update the terms
List<ThesaurusTerm> returnTerms = new ArrayList<ThesaurusTerm>();
for (ThesaurusTerm thesaurusTerm : terms) {
if (StringUtils.isEmpty(thesaurusTerm.getIdentifier())){
logger.info("Creating a new term in DB");
thesaurusTerm.setConceptId(returnConcept);
returnTerms.add(thesaurusTermService.createThesaurusTerm(thesaurusTerm, user));
} else {
//Case of existing term
logger.info("Updating an existing term in DB");
+ thesaurusTerm.setConceptId(returnConcept);
returnTerms.add(thesaurusTermService.updateThesaurusTerm(thesaurusTerm, user));
}
}
//Return ThesaurusConceptView created/updated
return new ThesaurusConceptView(returnConcept, returnTerms);
}
/**
* @param source source to work with
* @return ThesaurusConcept
* @throws BusinessException
* This method extracts a ThesaurusConcept from a ThesaurusConceptView given in argument
*/
private ThesaurusConcept convertConcept(ThesaurusConceptView source) throws BusinessException {
ThesaurusConcept thesaurusConcept;
//Test if ThesaurusConcept already exists. If yes we get it, if no we create a new one
if ("".equals(source.getIdentifier())) {
thesaurusConcept = new ThesaurusConcept();
thesaurusConcept.setCreated(DateUtil.nowDate());
thesaurusConcept.setModified(DateUtil.nowDate());
logger.info("Creating a new concept");
} else {
thesaurusConcept = thesaurusConceptService.getThesaurusConceptById(source.getIdentifier());
logger.info("Getting an existing concept");
}
if ("".equals(source.getThesaurusId())){
throw new BusinessException("ThesaurusId is mandatory to save a concept");
} else {
Thesaurus thesaurus = new Thesaurus();
thesaurus = thesaurusService.getThesaurusById(source.getThesaurusId());
thesaurusConcept.setThesaurus(thesaurus);
}
thesaurusConcept.setModified(DateUtil.nowDate());
thesaurusConcept.setTopConcept(source.getTopconcept());
return thesaurusConcept;
}
/**
* @param source source to work with
* @return {@code List<ThesaurusTerm>}
* @throws BusinessException
* This method extracts a list of ThesaurusTerm from a ThesaurusConceptView given in argument
*/
private List<ThesaurusTerm> convertTermViewsInTerms(ThesaurusConceptView source) throws BusinessException {
List<ThesaurusTermView> termViews = source.getTerms();
List<ThesaurusTerm> terms = new ArrayList<ThesaurusTerm>();
for (ThesaurusTermView thesaurusTermView : termViews) {
terms.add(termViewConverter.convert(thesaurusTermView));
}
return terms;
}
}
| true | true | public ThesaurusConceptView updateConcept(ThesaurusConceptView thesaurusConceptViewJAXBElement) throws BusinessException {
ThesaurusConcept convertedConcept = convertConcept(thesaurusConceptViewJAXBElement);
List <ThesaurusTerm> terms = convertTermViewsInTerms(thesaurusConceptViewJAXBElement);
logger.info("Number of converted terms : " + terms.size());
List <ThesaurusTerm> preferedTerm = thesaurusTermService.getPreferedTerms(terms);
//Business rule : a concept must have at least 1 term
if (preferedTerm.size() == 0) {
throw new BusinessException("A concept must have a prefered term");
}
//Business rule : a concept mustn't have more than one prefered term
if (preferedTerm.size() > 1) {
throw new BusinessException("A concept must have at only one prefered term");
}
String principal = "unknown";
if (context != null) {
principal = context.getHttpServletRequest().getRemoteAddr();
}
IUser user = new SimpleUserImpl();
user.setName(principal);
//We save or update the concept
ThesaurusConcept returnConcept = null;
if (StringUtils.isEmpty(convertedConcept.getIdentifier())) {
logger.info("Creating a new concept in DB");
returnConcept = thesaurusConceptService.createThesaurusConcept(convertedConcept, user);
} else {
//Case of existing concept
logger.info("Updating an existing concept in DB");
returnConcept = thesaurusConceptService.updateThesaurusConcept(convertedConcept, user);
}
//We save or update the terms
List<ThesaurusTerm> returnTerms = new ArrayList<ThesaurusTerm>();
for (ThesaurusTerm thesaurusTerm : terms) {
if (StringUtils.isEmpty(thesaurusTerm.getIdentifier())){
logger.info("Creating a new term in DB");
thesaurusTerm.setConceptId(returnConcept);
returnTerms.add(thesaurusTermService.createThesaurusTerm(thesaurusTerm, user));
} else {
//Case of existing term
logger.info("Updating an existing term in DB");
returnTerms.add(thesaurusTermService.updateThesaurusTerm(thesaurusTerm, user));
}
}
//Return ThesaurusConceptView created/updated
return new ThesaurusConceptView(returnConcept, returnTerms);
}
| public ThesaurusConceptView updateConcept(ThesaurusConceptView thesaurusConceptViewJAXBElement) throws BusinessException {
ThesaurusConcept convertedConcept = convertConcept(thesaurusConceptViewJAXBElement);
List <ThesaurusTerm> terms = convertTermViewsInTerms(thesaurusConceptViewJAXBElement);
logger.info("Number of converted terms : " + terms.size());
List <ThesaurusTerm> preferedTerm = thesaurusTermService.getPreferedTerms(terms);
//Business rule : a concept must have at least 1 term
if (preferedTerm.size() == 0) {
throw new BusinessException("A concept must have a prefered term");
}
//Business rule : a concept mustn't have more than one prefered term
if (preferedTerm.size() > 1) {
throw new BusinessException("A concept must have at only one prefered term");
}
String principal = "unknown";
if (context != null) {
principal = context.getHttpServletRequest().getRemoteAddr();
}
IUser user = new SimpleUserImpl();
user.setName(principal);
//We save or update the concept
ThesaurusConcept returnConcept = null;
if (StringUtils.isEmpty(convertedConcept.getIdentifier())) {
logger.info("Creating a new concept in DB");
returnConcept = thesaurusConceptService.createThesaurusConcept(convertedConcept, user);
} else {
//Case of existing concept
logger.info("Updating an existing concept in DB");
returnConcept = thesaurusConceptService.updateThesaurusConcept(convertedConcept, user);
}
//We save or update the terms
List<ThesaurusTerm> returnTerms = new ArrayList<ThesaurusTerm>();
for (ThesaurusTerm thesaurusTerm : terms) {
if (StringUtils.isEmpty(thesaurusTerm.getIdentifier())){
logger.info("Creating a new term in DB");
thesaurusTerm.setConceptId(returnConcept);
returnTerms.add(thesaurusTermService.createThesaurusTerm(thesaurusTerm, user));
} else {
//Case of existing term
logger.info("Updating an existing term in DB");
thesaurusTerm.setConceptId(returnConcept);
returnTerms.add(thesaurusTermService.updateThesaurusTerm(thesaurusTerm, user));
}
}
//Return ThesaurusConceptView created/updated
return new ThesaurusConceptView(returnConcept, returnTerms);
}
|
diff --git a/runtime/src/main/java/org/qi4j/runtime/resolution/KeyMatcher.java b/runtime/src/main/java/org/qi4j/runtime/resolution/KeyMatcher.java
index 9d39dc369..07a717111 100644
--- a/runtime/src/main/java/org/qi4j/runtime/resolution/KeyMatcher.java
+++ b/runtime/src/main/java/org/qi4j/runtime/resolution/KeyMatcher.java
@@ -1,44 +1,47 @@
package org.qi4j.runtime.resolution;
import org.qi4j.api.model.DependencyKey;
import org.qi4j.api.model.InjectionKey;
/**
* TODO
*/
public class KeyMatcher
{
public boolean matches( DependencyKey dependency, InjectionKey injectedObject )
{
// Match raw types (e.g. Iterable<Foo> matches List<Foo> and Iterable<Foo>)
if( !dependency.getRawType().isAssignableFrom( injectedObject.getRawType() ) )
{
return false;
}
// Match dependent types, if set
if( injectedObject.getDependentType() != null && !dependency.getDependentType().equals( injectedObject.getDependentType() ) )
{
- return false;
+ if( !dependency.getDependentType().isAssignableFrom( injectedObject.getDependentType() ) )
+ {
+ return false;
+ }
}
// Match names, if set
if( injectedObject.getName() != null )
{
// if injection key has a name, the name must match dependency key
if( dependency.getName() == null || !dependency.getName().equals( injectedObject.getName() ) )
{
return false;
}
}
// Match type - injecting subtypes is ok
if( !dependency.getDependencyType().isAssignableFrom( injectedObject.getDependencyType() ) )
{
return false;
}
// The keys match!
return true;
}
}
| true | true | public boolean matches( DependencyKey dependency, InjectionKey injectedObject )
{
// Match raw types (e.g. Iterable<Foo> matches List<Foo> and Iterable<Foo>)
if( !dependency.getRawType().isAssignableFrom( injectedObject.getRawType() ) )
{
return false;
}
// Match dependent types, if set
if( injectedObject.getDependentType() != null && !dependency.getDependentType().equals( injectedObject.getDependentType() ) )
{
return false;
}
// Match names, if set
if( injectedObject.getName() != null )
{
// if injection key has a name, the name must match dependency key
if( dependency.getName() == null || !dependency.getName().equals( injectedObject.getName() ) )
{
return false;
}
}
// Match type - injecting subtypes is ok
if( !dependency.getDependencyType().isAssignableFrom( injectedObject.getDependencyType() ) )
{
return false;
}
// The keys match!
return true;
}
| public boolean matches( DependencyKey dependency, InjectionKey injectedObject )
{
// Match raw types (e.g. Iterable<Foo> matches List<Foo> and Iterable<Foo>)
if( !dependency.getRawType().isAssignableFrom( injectedObject.getRawType() ) )
{
return false;
}
// Match dependent types, if set
if( injectedObject.getDependentType() != null && !dependency.getDependentType().equals( injectedObject.getDependentType() ) )
{
if( !dependency.getDependentType().isAssignableFrom( injectedObject.getDependentType() ) )
{
return false;
}
}
// Match names, if set
if( injectedObject.getName() != null )
{
// if injection key has a name, the name must match dependency key
if( dependency.getName() == null || !dependency.getName().equals( injectedObject.getName() ) )
{
return false;
}
}
// Match type - injecting subtypes is ok
if( !dependency.getDependencyType().isAssignableFrom( injectedObject.getDependencyType() ) )
{
return false;
}
// The keys match!
return true;
}
|
diff --git a/jabox/src/main/java/org/jabox/webapp/pages/BasePage.java b/jabox/src/main/java/org/jabox/webapp/pages/BasePage.java
index d7803406..e1e713a8 100644
--- a/jabox/src/main/java/org/jabox/webapp/pages/BasePage.java
+++ b/jabox/src/main/java/org/jabox/webapp/pages/BasePage.java
@@ -1,78 +1,75 @@
/*
* Jabox Open Source Version
* Copyright (C) 2009-2010 Dimitris Kapanidis
*
* This file is part of Jabox
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package org.jabox.webapp.pages;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.border.Border;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.jabox.webapp.borders.JaboxBorder;
public abstract class BasePage extends WebPage {
private static final long serialVersionUID = 8165952253551263784L;
@Override
public void renderHead(final IHeaderResponse response) {
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/jquery.tools.min.js"));
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/tooltips.js"));
// response.renderCSSReference(new PackageResourceReference(
// BasePage.class, "css/wicket.css"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/widgets.js"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/jquery.js"));
- response
- .renderJavaScriptReference(new JavaScriptResourceReference(
- BasePage.class, "js/bootstrap.js"));
}
private Border border;
public BasePage() {
}
public BasePage add(final Component child) {
// Add children of the page to the page's border component
if (border == null) {
// Create border and add it to the page
border = new JaboxBorder();
super.add(border);
}
border.add(child);
return this;
}
@Override
public MarkupContainer removeAll() {
border.removeAll();
return this;
}
@Override
public MarkupContainer replace(final Component child) {
return border.replace(child);
}
}
| true | true | public void renderHead(final IHeaderResponse response) {
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/jquery.tools.min.js"));
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/tooltips.js"));
// response.renderCSSReference(new PackageResourceReference(
// BasePage.class, "css/wicket.css"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/widgets.js"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/jquery.js"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/bootstrap.js"));
}
| public void renderHead(final IHeaderResponse response) {
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/jquery.tools.min.js"));
// response.renderJavaScriptReference(new JavaScriptResourceReference(
// BasePage.class, "js/tooltips.js"));
// response.renderCSSReference(new PackageResourceReference(
// BasePage.class, "css/wicket.css"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/widgets.js"));
response
.renderJavaScriptReference(new JavaScriptResourceReference(
BasePage.class, "js/jquery.js"));
}
|
diff --git a/picasso/src/main/java/com/squareup/picasso/ContactsPhotoBitmapHunter.java b/picasso/src/main/java/com/squareup/picasso/ContactsPhotoBitmapHunter.java
index c4e3c4f..27434d3 100644
--- a/picasso/src/main/java/com/squareup/picasso/ContactsPhotoBitmapHunter.java
+++ b/picasso/src/main/java/com/squareup/picasso/ContactsPhotoBitmapHunter.java
@@ -1,136 +1,136 @@
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.UriMatcher;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import java.io.IOException;
import java.io.InputStream;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.provider.ContactsContract.Contacts.openContactPhotoInputStream;
import static com.squareup.picasso.Picasso.LoadedFrom.DISK;
class ContactsPhotoBitmapHunter extends BitmapHunter {
/**
a lookup uri (e.g. content://com.android.contacts/contacts/lookup/3570i61d948d30808e537 )
*/
private static final int ID_LOOKUP = 1;
/**
a contact thumbnail uri (e.g. content://com.android.contacts/contacts/38/photo)
*/
private static final int ID_THUMBNAIL = 2;
/**
a contact uri (e.g. content://com.android.contacts/contacts/38)
*/
private static final int ID_CONTACT = 3;
/**
a contact display photo (high resolution) uri
(e.g. content://com.android.contacts/display_photo/5)
*/
private static final int ID_DISPLAY_PHOTO = 4;
static final UriMatcher matcher;
static {
matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", ID_LOOKUP);
matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/photo", ID_THUMBNAIL);
matcher.addURI(ContactsContract.AUTHORITY, "contacts/#", ID_CONTACT);
matcher.addURI(ContactsContract.AUTHORITY, "display_photo/#", ID_DISPLAY_PHOTO);
}
final Context context;
ContactsPhotoBitmapHunter(Context context, Picasso picasso, Dispatcher dispatcher, Cache cache,
Stats stats, Action action) {
super(picasso, dispatcher, cache, stats, action);
this.context = context;
}
@Override Bitmap decode(Request data)
throws IOException {
InputStream is = null;
try {
is = getInputStream();
return decodeStream(is, data);
} finally {
Utils.closeQuietly(is);
}
}
@Override Picasso.LoadedFrom getLoadedFrom() {
return DISK;
}
private InputStream getInputStream() throws IOException {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = getData().uri;
switch (matcher.match(uri)) {
case ID_LOOKUP:
uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
if (null == uri) {
return null;
}
// Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
case ID_CONTACT:
if (SDK_INT < ICE_CREAM_SANDWICH) {
return openContactPhotoInputStream(contentResolver, uri);
} else {
return ContactPhotoStreamIcs.get(contentResolver, uri);
}
case ID_THUMBNAIL:
case ID_DISPLAY_PHOTO:
return contentResolver.openInputStream(uri);
default:
- throw new IllegalStateException ("Invalid uri: " + uri);
+ throw new IllegalStateException("Invalid uri: " + uri);
}
}
private Bitmap decodeStream(InputStream stream, Request data) throws IOException {
if (stream == null) {
return null;
}
BitmapFactory.Options options = null;
if (data.hasSize()) {
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream is = getInputStream();
try {
BitmapFactory.decodeStream(is, null, options);
} finally {
Utils.closeQuietly(is);
}
calculateInSampleSize(data.targetWidth, data.targetHeight, options);
}
return BitmapFactory.decodeStream(stream, null, options);
}
@TargetApi(ICE_CREAM_SANDWICH)
private static class ContactPhotoStreamIcs {
static InputStream get(ContentResolver contentResolver, Uri uri) {
return openContactPhotoInputStream(contentResolver, uri, true);
}
}
}
| true | true | private InputStream getInputStream() throws IOException {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = getData().uri;
switch (matcher.match(uri)) {
case ID_LOOKUP:
uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
if (null == uri) {
return null;
}
// Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
case ID_CONTACT:
if (SDK_INT < ICE_CREAM_SANDWICH) {
return openContactPhotoInputStream(contentResolver, uri);
} else {
return ContactPhotoStreamIcs.get(contentResolver, uri);
}
case ID_THUMBNAIL:
case ID_DISPLAY_PHOTO:
return contentResolver.openInputStream(uri);
default:
throw new IllegalStateException ("Invalid uri: " + uri);
}
}
| private InputStream getInputStream() throws IOException {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = getData().uri;
switch (matcher.match(uri)) {
case ID_LOOKUP:
uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
if (null == uri) {
return null;
}
// Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
case ID_CONTACT:
if (SDK_INT < ICE_CREAM_SANDWICH) {
return openContactPhotoInputStream(contentResolver, uri);
} else {
return ContactPhotoStreamIcs.get(contentResolver, uri);
}
case ID_THUMBNAIL:
case ID_DISPLAY_PHOTO:
return contentResolver.openInputStream(uri);
default:
throw new IllegalStateException("Invalid uri: " + uri);
}
}
|
diff --git a/contrib/Plugin.java b/contrib/Plugin.java
index 48935c4..7347729 100644
--- a/contrib/Plugin.java
+++ b/contrib/Plugin.java
@@ -1,342 +1,342 @@
import uk.co.uwcs.choob.*;
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.util.regex.*;
import java.util.*;
public class Plugin
{
public String[] info()
{
return new String[] {
"Plugin loader/manipulator.",
"The Choob Team",
"[email protected]",
"$Rev$$Date$"
};
}
private Modules mods;
private IRCInterface irc;
public Plugin(Modules mods, IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
public String[] helpCommandLoad = {
"Load a plugin.",
"[<Name>] <URL>",
"<Name> is an optional name for the plugin (if you don't give one, it'll be guessed from the URL)",
"<URL> is the URL from which to load the plugin"
};
public void commandLoad( Message mes )
{
// First, do auth!
List<String> params = mods.util.getParams( mes );
String url="";
String classname="";
if (params.size() == 2)
{
Pattern pa;
Matcher ma;
url=params.get(1);
pa = Pattern.compile("^.*\\/([^\\/]+)\\.(java|js)$");
ma = pa.matcher(url);
if (ma.matches())
classname=ma.group(1);
else
{
irc.sendContextReply(mes, "Unable to parse url (" + url + ") -> classname, please specify.");
return;
}
}
else
{
if( params.size() != 3 )
{
irc.sendContextReply(mes, "Syntax: [classname] url");
return;
}
else
{
url=params.get(2);
classname=params.get(1);
if ( classname.indexOf("/") != -1 )
{
irc.sendContextReply(mes, "Arguments the other way around, you spoon.");
return;
}
}
}
mods.security.checkNickPerm( new ChoobPermission( "plugin.load." + classname.toLowerCase() ), mes );
try
{
mods.security.addGroup("plugin." + classname.toLowerCase());
}
catch (ChoobException e)
{
// TODO: Make a groupExists() or something so we don't need to squelch this
}
irc.sendContextReply(mes, "Loading plugin '" + classname + "'...");
try
{
mods.plugin.addPlugin(classname, url);
String[] info;
info = getInfo(classname);
if (info.length >= 3)
irc.sendContextReply(mes, "Plugin loaded OK, new version is " + info[3] + ".");
else
irc.sendContextReply(mes, "Plugin loaded OK, but has missing info.");
}
catch (ChoobNoSuchCallException e)
{
- irc.sendContextReply(mes, "Plugin loaded, but.. not there?");
+ irc.sendContextReply(mes, "Plugin loaded, but doesn't have any info.");
}
catch (ClassCastException e)
{
irc.sendContextReply(mes, "Plugin loaded, but has invalid info.");
}
catch (Exception e)
{
irc.sendContextReply(mes, "Error loading plugin, see log for more details. " + e);
e.printStackTrace();
}
}
public String[] helpCommandReload = {
"Reloads an existing plugin.",
"<Name>",
"<Name> is the name of the plugin"
};
public void commandReload(Message mes) {
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.Reload " + helpCommandReload[1] + "'.");
return;
}
String pluginName = params.get(1);
mods.security.checkNickPerm(new ChoobPermission("plugin.load." + pluginName.toLowerCase()), mes);
irc.sendContextReply(mes, "Reloading plugin '" + pluginName + "'...");
try {
mods.plugin.reloadPlugin(pluginName);
String[] info;
info = getInfo(pluginName);
if (info.length >= 3)
irc.sendContextReply(mes, "Plugin reloaded OK, new version is " + info[3] + ".");
else
irc.sendContextReply(mes, "Plugin reloaded OK, but has missing info.");
}
catch (ChoobNoSuchCallException e)
{
irc.sendContextReply(mes, "Plugin reloaded, but.. not there?");
}
catch (ClassCastException e)
{
irc.sendContextReply(mes, "Plugin reloaded, but has invalid info.");
} catch (Exception e) {
irc.sendContextReply(mes, "Error reloading plugin, see log for more details. " + e);
e.printStackTrace();
}
}
public String[] helpCommandDetach = {
"Stops a plugin executing any new tasks.",
"<Name>",
"<Name> is the name of the plugin"
};
public void commandDetach(Message mes) {
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.Detach " + helpCommandDetach[1] + "'.");
return;
}
String pluginName = params.get(1);
mods.security.checkNickPerm(new ChoobPermission("plugin.unload." + pluginName.toLowerCase()), mes);
try {
mods.plugin.detachPlugin(pluginName);
irc.sendContextReply(mes, "Plugin detached OK! (It might still be running stuff, though.)");
} catch (ChoobNoSuchPluginException e) {
irc.sendContextReply(mes, "Plugin " + pluginName + " isn't loaded!");
}
}
public String[] helpCommandSetCore = {
"Makes a plugin a core plugin.",
"<Name>",
"<Name> is the name of the plugin"
};
public void commandSetCore(Message mes) {
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.SetCore " + helpCommandSetCore[1] + "'.");
return;
}
String pluginName = params.get(1);
mods.security.checkNickPerm(new ChoobPermission("plugin.core"), mes);
try {
mods.plugin.setCorePlugin(pluginName, true);
irc.sendContextReply(mes, "Plugin is now core!");
} catch (ChoobNoSuchPluginException e) {
irc.sendContextReply(mes, "Plugin " + pluginName + " doesn't exist!");
}
}
public String[] helpCommandUnsetCore = {
"Makes a core plugin no longer core.",
"<Name>",
"<Name> is the name of the plugin"
};
public void commandUnsetCore(Message mes) {
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.UnsetCore " + helpCommandUnsetCore[1] + "'.");
return;
}
String pluginName = params.get(1);
mods.security.checkNickPerm(new ChoobPermission("plugin.core"), mes);
try {
mods.plugin.setCorePlugin(pluginName, false);
irc.sendContextReply(mes, "Plugin is no longer core!");
} catch (ChoobNoSuchPluginException e) {
irc.sendContextReply(mes, "Plugin " + pluginName + " doesn't exist!");
}
}
public String[] helpCommandList = {
"List all known plugins."
};
public void commandList(Message mes) {
// Get all plugins.
String[] plugins = mods.plugin.getLoadedPlugins();
Arrays.sort(plugins);
// Hash all core plugins.
String[] corePlugins = mods.plugin.getAllPlugins(true);
Set<String> coreSet = new HashSet<String>();
for(int i=0; i<corePlugins.length; i++)
coreSet.add(corePlugins[i].toLowerCase());
StringBuilder buf = new StringBuilder();
buf.append("Plugin list (core marked with *): ");
for(int i=0; i<plugins.length; i++)
{
buf.append(plugins[i]);
if (coreSet.contains(plugins[i].toLowerCase()))
buf.append("*");
if (i == plugins.length - 2)
buf.append(" and ");
else if (i != plugins.length - 1)
buf.append(", ");
}
buf.append(".");
irc.sendContextReply(mes, buf.toString());
}
private String[] getInfo(String pluginName) throws ChoobNoSuchCallException, ClassCastException
{
return (String[])mods.plugin.callGeneric(pluginName, "Info", "");
}
public String[] helpCommandInfo = {
"Get info about a plugin.",
"<Plugin>",
"<Plugin> is the name of the plugin"
};
public void commandInfo(Message mes)
{
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.Info " + helpCommandInfo[1] + "'.");
return;
}
String pluginName = params.get(1);
String[] info;
try
{
info = getInfo(pluginName);
}
catch (ChoobNoSuchCallException e)
{
irc.sendContextReply(mes, "Oi! Plugin " + pluginName + " isn't loaded. (Or has no info...)");
return;
}
catch (ClassCastException e)
{
irc.sendContextReply(mes, "Plugin " + pluginName + " had invalid info!");
return;
}
irc.sendContextReply(mes, pluginName + ": " + info[0] + " By " + info[1] + " <" + info[2] + ">; version is " + info[3] + ".");
}
public String[] helpCommandSource = {
"Get the source URL for a plugin.",
"<Plugin>",
"<Plugin> is the name of the plugin"
};
public void commandSource(Message mes)
{
List<String> params = mods.util.getParams(mes);
if (params.size() == 1)
{
irc.sendContextReply(mes, "Syntax: 'Plugin.Source " + helpCommandInfo[1] + "'.");
return;
}
String[] plugins = mods.plugin.getLoadedPlugins();
String pluginName = params.get(1);
String pluginNameL = pluginName.toLowerCase();
String source;
try
{
source = mods.plugin.getPluginSource(pluginName);
}
catch (ChoobNoSuchPluginException e)
{
irc.sendContextReply(mes, "Plugin " + pluginName + " has never been loaded.");
return;
}
boolean loaded = false;
for (int i = 0; i < plugins.length; i++) {
if (plugins[i].toLowerCase().equals(pluginNameL)) {
loaded = true;
break;
}
}
if (loaded) {
irc.sendContextReply(mes, pluginName + " is loaded from <" + source + ">.");
} else {
irc.sendContextReply(mes, pluginName + " was last loaded from <" + source + ">.");
}
}
}
| true | true | public void commandLoad( Message mes )
{
// First, do auth!
List<String> params = mods.util.getParams( mes );
String url="";
String classname="";
if (params.size() == 2)
{
Pattern pa;
Matcher ma;
url=params.get(1);
pa = Pattern.compile("^.*\\/([^\\/]+)\\.(java|js)$");
ma = pa.matcher(url);
if (ma.matches())
classname=ma.group(1);
else
{
irc.sendContextReply(mes, "Unable to parse url (" + url + ") -> classname, please specify.");
return;
}
}
else
{
if( params.size() != 3 )
{
irc.sendContextReply(mes, "Syntax: [classname] url");
return;
}
else
{
url=params.get(2);
classname=params.get(1);
if ( classname.indexOf("/") != -1 )
{
irc.sendContextReply(mes, "Arguments the other way around, you spoon.");
return;
}
}
}
mods.security.checkNickPerm( new ChoobPermission( "plugin.load." + classname.toLowerCase() ), mes );
try
{
mods.security.addGroup("plugin." + classname.toLowerCase());
}
catch (ChoobException e)
{
// TODO: Make a groupExists() or something so we don't need to squelch this
}
irc.sendContextReply(mes, "Loading plugin '" + classname + "'...");
try
{
mods.plugin.addPlugin(classname, url);
String[] info;
info = getInfo(classname);
if (info.length >= 3)
irc.sendContextReply(mes, "Plugin loaded OK, new version is " + info[3] + ".");
else
irc.sendContextReply(mes, "Plugin loaded OK, but has missing info.");
}
catch (ChoobNoSuchCallException e)
{
irc.sendContextReply(mes, "Plugin loaded, but.. not there?");
}
catch (ClassCastException e)
{
irc.sendContextReply(mes, "Plugin loaded, but has invalid info.");
}
catch (Exception e)
{
irc.sendContextReply(mes, "Error loading plugin, see log for more details. " + e);
e.printStackTrace();
}
}
| public void commandLoad( Message mes )
{
// First, do auth!
List<String> params = mods.util.getParams( mes );
String url="";
String classname="";
if (params.size() == 2)
{
Pattern pa;
Matcher ma;
url=params.get(1);
pa = Pattern.compile("^.*\\/([^\\/]+)\\.(java|js)$");
ma = pa.matcher(url);
if (ma.matches())
classname=ma.group(1);
else
{
irc.sendContextReply(mes, "Unable to parse url (" + url + ") -> classname, please specify.");
return;
}
}
else
{
if( params.size() != 3 )
{
irc.sendContextReply(mes, "Syntax: [classname] url");
return;
}
else
{
url=params.get(2);
classname=params.get(1);
if ( classname.indexOf("/") != -1 )
{
irc.sendContextReply(mes, "Arguments the other way around, you spoon.");
return;
}
}
}
mods.security.checkNickPerm( new ChoobPermission( "plugin.load." + classname.toLowerCase() ), mes );
try
{
mods.security.addGroup("plugin." + classname.toLowerCase());
}
catch (ChoobException e)
{
// TODO: Make a groupExists() or something so we don't need to squelch this
}
irc.sendContextReply(mes, "Loading plugin '" + classname + "'...");
try
{
mods.plugin.addPlugin(classname, url);
String[] info;
info = getInfo(classname);
if (info.length >= 3)
irc.sendContextReply(mes, "Plugin loaded OK, new version is " + info[3] + ".");
else
irc.sendContextReply(mes, "Plugin loaded OK, but has missing info.");
}
catch (ChoobNoSuchCallException e)
{
irc.sendContextReply(mes, "Plugin loaded, but doesn't have any info.");
}
catch (ClassCastException e)
{
irc.sendContextReply(mes, "Plugin loaded, but has invalid info.");
}
catch (Exception e)
{
irc.sendContextReply(mes, "Error loading plugin, see log for more details. " + e);
e.printStackTrace();
}
}
|
diff --git a/sveditor/plugins/net.sf.sveditor.ui/src/net/sf/sveditor/ui/svcp/SVTreeLabelProvider.java b/sveditor/plugins/net.sf.sveditor.ui/src/net/sf/sveditor/ui/svcp/SVTreeLabelProvider.java
index b6081f9e..3af5a9c0 100644
--- a/sveditor/plugins/net.sf.sveditor.ui/src/net/sf/sveditor/ui/svcp/SVTreeLabelProvider.java
+++ b/sveditor/plugins/net.sf.sveditor.ui/src/net/sf/sveditor/ui/svcp/SVTreeLabelProvider.java
@@ -1,244 +1,252 @@
/****************************************************************************
* Copyright (c) 2008-2010 Matthew Ballance and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Ballance - initial implementation
****************************************************************************/
package net.sf.sveditor.ui.svcp;
import net.sf.sveditor.core.db.ISVDBItemBase;
import net.sf.sveditor.core.db.ISVDBNamedItem;
import net.sf.sveditor.core.db.SVDBClassDecl;
import net.sf.sveditor.core.db.SVDBFunction;
import net.sf.sveditor.core.db.SVDBGenerateIf;
import net.sf.sveditor.core.db.SVDBItemType;
import net.sf.sveditor.core.db.SVDBModIfcClassParam;
import net.sf.sveditor.core.db.SVDBModIfcDecl;
import net.sf.sveditor.core.db.SVDBModIfcInst;
import net.sf.sveditor.core.db.SVDBModIfcInstItem;
import net.sf.sveditor.core.db.SVDBParamValueAssign;
import net.sf.sveditor.core.db.SVDBTask;
import net.sf.sveditor.core.db.SVDBTypeInfo;
import net.sf.sveditor.core.db.SVDBTypeInfoUserDef;
import net.sf.sveditor.core.db.index.SVDBDeclCacheItem;
import net.sf.sveditor.core.db.stmt.SVDBAlwaysStmt;
import net.sf.sveditor.core.db.stmt.SVDBEventControlStmt;
import net.sf.sveditor.core.db.stmt.SVDBExportItem;
import net.sf.sveditor.core.db.stmt.SVDBImportItem;
import net.sf.sveditor.core.db.stmt.SVDBParamPortDecl;
import net.sf.sveditor.core.db.stmt.SVDBVarDeclItem;
import net.sf.sveditor.core.db.stmt.SVDBVarDeclStmt;
import net.sf.sveditor.ui.SVDBIconUtils;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.model.WorkbenchLabelProvider;
public class SVTreeLabelProvider extends LabelProvider implements IStyledLabelProvider {
protected boolean fShowFunctionRetType;
private WorkbenchLabelProvider fLabelProvider;
public SVTreeLabelProvider() {
fLabelProvider = new WorkbenchLabelProvider();
fShowFunctionRetType = true;
}
@Override
public Image getImage(Object element) {
if (element instanceof ISVDBItemBase) {
return SVDBIconUtils.getIcon((ISVDBItemBase)element);
} else if (element instanceof SVDBDeclCacheItem) {
SVDBDeclCacheItem item = (SVDBDeclCacheItem)element;
return SVDBIconUtils.getIcon(item.getType());
} else {
return super.getImage(element);
}
}
public StyledString getStyledText(Object element) {
if (element == null) {
return new StyledString("null");
}
if (element instanceof SVDBDeclCacheItem) {
SVDBDeclCacheItem item = (SVDBDeclCacheItem)element;
return new StyledString(item.getName());
} else if (element instanceof SVDBVarDeclItem) {
SVDBVarDeclItem var = (SVDBVarDeclItem)element;
SVDBVarDeclStmt var_r = var.getParent();
StyledString ret = new StyledString(var.getName());
if (var_r.getTypeInfo() != null) {
ret.append(" : " + var_r.getTypeName(), StyledString.QUALIFIER_STYLER);
SVDBTypeInfo type = var_r.getTypeInfo();
if (type.getType() == SVDBItemType.TypeInfoUserDef) {
SVDBTypeInfoUserDef cls = (SVDBTypeInfoUserDef)type;
if (cls.getParameters() != null &&
cls.getParameters().getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<cls.getParameters().getParameters().size(); i++) {
SVDBParamValueAssign p =
cls.getParameters().getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < cls.getParameters().getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
}
}
return ret;
} else if (element instanceof ISVDBNamedItem) {
StyledString ret = new StyledString(((ISVDBNamedItem)element).getName());
ISVDBNamedItem ni = (ISVDBNamedItem)element;
if (ni.getType().isElemOf(SVDBItemType.Task, SVDBItemType.Function)) {
SVDBTask tf = (SVDBTask)element;
ret.append("(");
for (int i=0; i<tf.getParams().size(); i++) {
SVDBParamPortDecl p = tf.getParams().get(i);
if (p.getTypeInfo() != null) {
ret.append(p.getTypeInfo().toString());
}
if (i+1 < tf.getParams().size()) {
ret.append(", ");
}
}
ret.append(")");
if (tf.getType() == SVDBItemType.Function) {
SVDBFunction f = (SVDBFunction)tf;
if (f.getReturnType() != null &&
!f.getReturnType().equals("void") &&
fShowFunctionRetType) {
ret.append(": " + f.getReturnType(), StyledString.QUALIFIER_STYLER);
}
}
} else if (element instanceof SVDBModIfcDecl) {
SVDBModIfcDecl decl = (SVDBModIfcDecl)element;
if (decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (element instanceof SVDBClassDecl) {
SVDBClassDecl decl = (SVDBClassDecl)element;
if (decl.getParameters() != null && decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (ni.getType() == SVDBItemType.ModIfcInstItem) {
SVDBModIfcInstItem mod_item = (SVDBModIfcInstItem)ni;
SVDBModIfcInst mod_inst = (SVDBModIfcInst)mod_item.getParent();
ret.append(" : " + mod_inst.getTypeName(), StyledString.QUALIFIER_STYLER);
} else if (ni.getType() == SVDBItemType.CoverageOptionStmt) {
// SVDBCoverageOptionStmt option = (SVDBCoverageOptionStmt)ni;
ret.append(" : option", StyledString.QUALIFIER_STYLER);
} else {
// ret = new StyledString("UNKNOWN NamedItem " + ((ISVDBNamedItem)element).getType());
}
return ret;
} else if (element instanceof SVDBGenerateIf) {
SVDBGenerateIf it = (SVDBGenerateIf)element;
- return (new StyledString (it.fName));
+ if (it.fName != null) {
+ return (new StyledString (it.fName));
+ }
+ // This will occur if a if statement within an initial block etc is suddenly recognized as a "generateif"
+ // The parser doesn't do a good job of casting from the if to the genif, and fname seems to be off in the weeds
+ // TODO: Fix this properly - See Tracker # 3591399
+ else {
+ return (new StyledString ("if"));
+ }
} else if (element instanceof ISVDBItemBase) {
ISVDBItemBase it = (ISVDBItemBase)element;
StyledString ret = null;
if (it.getType() == SVDBItemType.AlwaysStmt) {
SVDBAlwaysStmt always = (SVDBAlwaysStmt)it;
if (always.getBody() != null && always.getBody().getType() == SVDBItemType.EventControlStmt) {
SVDBEventControlStmt stmt = (SVDBEventControlStmt)always.getBody();
ret = new StyledString(stmt.getExpr().toString().trim());
} else {
ret = new StyledString("always");
}
} else if (it.getType() == SVDBItemType.InitialStmt) {
ret = new StyledString("initial");
} else if (it.getType() == SVDBItemType.FinalStmt) {
ret = new StyledString("final");
} else if (it.getType() == SVDBItemType.ImportItem) {
SVDBImportItem imp = (SVDBImportItem)it;
ret = new StyledString("import " + imp.getImport());
} else if (it.getType() == SVDBItemType.ExportItem) {
SVDBExportItem exp = (SVDBExportItem)it;
ret = new StyledString("export " + exp.getExport());
}
if (ret == null) {
ret = new StyledString(element.toString());
}
return ret;
} else {
return new StyledString(element.toString());
}
}
@Override
public String getText(Object element) {
return getStyledText(element).toString();
}
@Override
public void addListener(ILabelProviderListener listener) {
fLabelProvider.addListener(listener);
}
@Override
public void removeListener(ILabelProviderListener listener) {
fLabelProvider.removeListener(listener);
}
@Override
public boolean isLabelProperty(Object element, String property) {
return fLabelProvider.isLabelProperty(element, property);
}
@Override
public void dispose() {
super.dispose();
fLabelProvider.dispose();
}
}
| true | true | public StyledString getStyledText(Object element) {
if (element == null) {
return new StyledString("null");
}
if (element instanceof SVDBDeclCacheItem) {
SVDBDeclCacheItem item = (SVDBDeclCacheItem)element;
return new StyledString(item.getName());
} else if (element instanceof SVDBVarDeclItem) {
SVDBVarDeclItem var = (SVDBVarDeclItem)element;
SVDBVarDeclStmt var_r = var.getParent();
StyledString ret = new StyledString(var.getName());
if (var_r.getTypeInfo() != null) {
ret.append(" : " + var_r.getTypeName(), StyledString.QUALIFIER_STYLER);
SVDBTypeInfo type = var_r.getTypeInfo();
if (type.getType() == SVDBItemType.TypeInfoUserDef) {
SVDBTypeInfoUserDef cls = (SVDBTypeInfoUserDef)type;
if (cls.getParameters() != null &&
cls.getParameters().getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<cls.getParameters().getParameters().size(); i++) {
SVDBParamValueAssign p =
cls.getParameters().getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < cls.getParameters().getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
}
}
return ret;
} else if (element instanceof ISVDBNamedItem) {
StyledString ret = new StyledString(((ISVDBNamedItem)element).getName());
ISVDBNamedItem ni = (ISVDBNamedItem)element;
if (ni.getType().isElemOf(SVDBItemType.Task, SVDBItemType.Function)) {
SVDBTask tf = (SVDBTask)element;
ret.append("(");
for (int i=0; i<tf.getParams().size(); i++) {
SVDBParamPortDecl p = tf.getParams().get(i);
if (p.getTypeInfo() != null) {
ret.append(p.getTypeInfo().toString());
}
if (i+1 < tf.getParams().size()) {
ret.append(", ");
}
}
ret.append(")");
if (tf.getType() == SVDBItemType.Function) {
SVDBFunction f = (SVDBFunction)tf;
if (f.getReturnType() != null &&
!f.getReturnType().equals("void") &&
fShowFunctionRetType) {
ret.append(": " + f.getReturnType(), StyledString.QUALIFIER_STYLER);
}
}
} else if (element instanceof SVDBModIfcDecl) {
SVDBModIfcDecl decl = (SVDBModIfcDecl)element;
if (decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (element instanceof SVDBClassDecl) {
SVDBClassDecl decl = (SVDBClassDecl)element;
if (decl.getParameters() != null && decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (ni.getType() == SVDBItemType.ModIfcInstItem) {
SVDBModIfcInstItem mod_item = (SVDBModIfcInstItem)ni;
SVDBModIfcInst mod_inst = (SVDBModIfcInst)mod_item.getParent();
ret.append(" : " + mod_inst.getTypeName(), StyledString.QUALIFIER_STYLER);
} else if (ni.getType() == SVDBItemType.CoverageOptionStmt) {
// SVDBCoverageOptionStmt option = (SVDBCoverageOptionStmt)ni;
ret.append(" : option", StyledString.QUALIFIER_STYLER);
} else {
// ret = new StyledString("UNKNOWN NamedItem " + ((ISVDBNamedItem)element).getType());
}
return ret;
} else if (element instanceof SVDBGenerateIf) {
SVDBGenerateIf it = (SVDBGenerateIf)element;
return (new StyledString (it.fName));
} else if (element instanceof ISVDBItemBase) {
ISVDBItemBase it = (ISVDBItemBase)element;
StyledString ret = null;
if (it.getType() == SVDBItemType.AlwaysStmt) {
SVDBAlwaysStmt always = (SVDBAlwaysStmt)it;
if (always.getBody() != null && always.getBody().getType() == SVDBItemType.EventControlStmt) {
SVDBEventControlStmt stmt = (SVDBEventControlStmt)always.getBody();
ret = new StyledString(stmt.getExpr().toString().trim());
} else {
ret = new StyledString("always");
}
} else if (it.getType() == SVDBItemType.InitialStmt) {
ret = new StyledString("initial");
} else if (it.getType() == SVDBItemType.FinalStmt) {
ret = new StyledString("final");
} else if (it.getType() == SVDBItemType.ImportItem) {
SVDBImportItem imp = (SVDBImportItem)it;
ret = new StyledString("import " + imp.getImport());
} else if (it.getType() == SVDBItemType.ExportItem) {
SVDBExportItem exp = (SVDBExportItem)it;
ret = new StyledString("export " + exp.getExport());
}
if (ret == null) {
ret = new StyledString(element.toString());
}
return ret;
} else {
return new StyledString(element.toString());
}
}
| public StyledString getStyledText(Object element) {
if (element == null) {
return new StyledString("null");
}
if (element instanceof SVDBDeclCacheItem) {
SVDBDeclCacheItem item = (SVDBDeclCacheItem)element;
return new StyledString(item.getName());
} else if (element instanceof SVDBVarDeclItem) {
SVDBVarDeclItem var = (SVDBVarDeclItem)element;
SVDBVarDeclStmt var_r = var.getParent();
StyledString ret = new StyledString(var.getName());
if (var_r.getTypeInfo() != null) {
ret.append(" : " + var_r.getTypeName(), StyledString.QUALIFIER_STYLER);
SVDBTypeInfo type = var_r.getTypeInfo();
if (type.getType() == SVDBItemType.TypeInfoUserDef) {
SVDBTypeInfoUserDef cls = (SVDBTypeInfoUserDef)type;
if (cls.getParameters() != null &&
cls.getParameters().getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<cls.getParameters().getParameters().size(); i++) {
SVDBParamValueAssign p =
cls.getParameters().getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < cls.getParameters().getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
}
}
return ret;
} else if (element instanceof ISVDBNamedItem) {
StyledString ret = new StyledString(((ISVDBNamedItem)element).getName());
ISVDBNamedItem ni = (ISVDBNamedItem)element;
if (ni.getType().isElemOf(SVDBItemType.Task, SVDBItemType.Function)) {
SVDBTask tf = (SVDBTask)element;
ret.append("(");
for (int i=0; i<tf.getParams().size(); i++) {
SVDBParamPortDecl p = tf.getParams().get(i);
if (p.getTypeInfo() != null) {
ret.append(p.getTypeInfo().toString());
}
if (i+1 < tf.getParams().size()) {
ret.append(", ");
}
}
ret.append(")");
if (tf.getType() == SVDBItemType.Function) {
SVDBFunction f = (SVDBFunction)tf;
if (f.getReturnType() != null &&
!f.getReturnType().equals("void") &&
fShowFunctionRetType) {
ret.append(": " + f.getReturnType(), StyledString.QUALIFIER_STYLER);
}
}
} else if (element instanceof SVDBModIfcDecl) {
SVDBModIfcDecl decl = (SVDBModIfcDecl)element;
if (decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (element instanceof SVDBClassDecl) {
SVDBClassDecl decl = (SVDBClassDecl)element;
if (decl.getParameters() != null && decl.getParameters().size() > 0) {
ret.append("<", StyledString.QUALIFIER_STYLER);
for (int i=0; i<decl.getParameters().size(); i++) {
SVDBModIfcClassParam p = decl.getParameters().get(i);
ret.append(p.getName(), StyledString.QUALIFIER_STYLER);
if (i+1 < decl.getParameters().size()) {
ret.append(", ", StyledString.QUALIFIER_STYLER);
}
}
ret.append(">", StyledString.QUALIFIER_STYLER);
}
} else if (ni.getType() == SVDBItemType.ModIfcInstItem) {
SVDBModIfcInstItem mod_item = (SVDBModIfcInstItem)ni;
SVDBModIfcInst mod_inst = (SVDBModIfcInst)mod_item.getParent();
ret.append(" : " + mod_inst.getTypeName(), StyledString.QUALIFIER_STYLER);
} else if (ni.getType() == SVDBItemType.CoverageOptionStmt) {
// SVDBCoverageOptionStmt option = (SVDBCoverageOptionStmt)ni;
ret.append(" : option", StyledString.QUALIFIER_STYLER);
} else {
// ret = new StyledString("UNKNOWN NamedItem " + ((ISVDBNamedItem)element).getType());
}
return ret;
} else if (element instanceof SVDBGenerateIf) {
SVDBGenerateIf it = (SVDBGenerateIf)element;
if (it.fName != null) {
return (new StyledString (it.fName));
}
// This will occur if a if statement within an initial block etc is suddenly recognized as a "generateif"
// The parser doesn't do a good job of casting from the if to the genif, and fname seems to be off in the weeds
// TODO: Fix this properly - See Tracker # 3591399
else {
return (new StyledString ("if"));
}
} else if (element instanceof ISVDBItemBase) {
ISVDBItemBase it = (ISVDBItemBase)element;
StyledString ret = null;
if (it.getType() == SVDBItemType.AlwaysStmt) {
SVDBAlwaysStmt always = (SVDBAlwaysStmt)it;
if (always.getBody() != null && always.getBody().getType() == SVDBItemType.EventControlStmt) {
SVDBEventControlStmt stmt = (SVDBEventControlStmt)always.getBody();
ret = new StyledString(stmt.getExpr().toString().trim());
} else {
ret = new StyledString("always");
}
} else if (it.getType() == SVDBItemType.InitialStmt) {
ret = new StyledString("initial");
} else if (it.getType() == SVDBItemType.FinalStmt) {
ret = new StyledString("final");
} else if (it.getType() == SVDBItemType.ImportItem) {
SVDBImportItem imp = (SVDBImportItem)it;
ret = new StyledString("import " + imp.getImport());
} else if (it.getType() == SVDBItemType.ExportItem) {
SVDBExportItem exp = (SVDBExportItem)it;
ret = new StyledString("export " + exp.getExport());
}
if (ret == null) {
ret = new StyledString(element.toString());
}
return ret;
} else {
return new StyledString(element.toString());
}
}
|
diff --git a/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java b/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
index 9b5c998..3522e7d 100644
--- a/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
+++ b/src/de/hotmail/gurkilein/bankcraft/MinecraftCommandListener.java
@@ -1,419 +1,419 @@
package de.hotmail.gurkilein.bankcraft;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.hotmail.gurkilein.bankcraft.banking.ExperienceBankingHandler;
import de.hotmail.gurkilein.bankcraft.banking.MoneyBankingHandler;
import de.hotmail.gurkilein.bankcraft.database.AccountDatabaseInterface;
import de.hotmail.gurkilein.bankcraft.database.DatabaseManagerInterface;
import de.hotmail.gurkilein.bankcraft.database.SignDatabaseInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.DatabaseManagerFlatFile;
import de.hotmail.gurkilein.bankcraft.database.flatfile.ExperienceFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.MoneyFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.flatfile.SignFlatFileInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.DatabaseManagerMysql;
import de.hotmail.gurkilein.bankcraft.database.mysql.ExperienceMysqlInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.MoneyMysqlInterface;
import de.hotmail.gurkilein.bankcraft.database.mysql.SignMysqlInterface;
public class MinecraftCommandListener implements CommandExecutor{
private Bankcraft bankcraft;
private ConfigurationHandler coHa;
public MinecraftCommandListener(Bankcraft bankcraft) {
this.bankcraft = bankcraft;
this.coHa = bankcraft.getConfigurationHandler();
}
@SuppressWarnings("unused")
private Bankcraft plugin;
public Double betrag;
public void sendHelp(Player p) {
p.sendMessage("---Bankcraft-Help---");
p.sendMessage("/bank "+coHa.getString("signAndCommand.help")+" Shows the help page.");
if (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.balance")+" PLAYER Shows your banked money.");
if (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.balancexp")+" PLAYER Shows your banked XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.deposit")+" AMOUNT Deposits money to your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.withdraw")+" AMOUNT Withdraws money from your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.depositxp")+" AMOUNT Deposits XP to your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.withdrawxp")+" AMOUNT Withdraws XP from your Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.transfer")+" PLAYER AMOUNT Transfers money to another Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.transferxp")+" PLAYER AMOUNT Transfers XP to another Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.interesttimer")+" Shows the remaining time until the next wave of interests.");
if (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.exchange")+" AMOUNT Exchanges money to XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.exchangexp")+" AMOUNT Exchanges XP to money.");
if (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.rankstats")+" Shows the richest players.");
if (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))
p.sendMessage("/bank "+coHa.getString("signAndCommand.rankstatsxp")+" Shows the players with the most experience banked.");
}
public void sendAdminHelp(Player p) {
p.sendMessage("---Bankcraft-AdminHelp---");
p.sendMessage("/bankadmin help Shows the help page.");
if (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.set")+" PLAYER AMOUNT Sets a players money.");
if (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.setxp")+" PLAYER AMOUNT Sets a players XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.grant")+" PLAYER AMOUNT Grants a Player money.");
if (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.grantxp")+" PLAYER AMOUNT Grants a player XP.");
if (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.clear")+" PLAYER Clears money from a players Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.clearxp")+" PLAYER Clears XP from a players Account.");
if (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.databaseimport")+" OLDDATA NEWDATA Moves data from one database type to another");
if (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))
p.sendMessage("/bankadmin "+coHa.getString("signAndCommand.admin.reloadconfig")+" Reloads the config of bankcraft.");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstats")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstatsxp")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[2]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
- }
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[2]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
}
}
+ }
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.reloadconfig")) && (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.reloadConfig();
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Config reloaded!");
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstats")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstatsxp")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[2]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[2]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
}
}
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.reloadconfig")) && (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.reloadConfig();
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Config reloaded!");
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String cmdlabel, String[] vars) {
Player p;
if (sender instanceof Player) {
p = (Player) sender;
if (cmdlabel.equalsIgnoreCase("bank") || cmdlabel.equalsIgnoreCase("bc")) {
if (vars.length == 0) {
sendHelp(p);
return true;
}
if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.help"))) {
sendHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.interesttimer")) && (Bankcraft.perms.has(p, "bankcraft.command.interesttimer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstats")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstats") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.rankstatsxp")) && (Bankcraft.perms.has(p, "bankcraft.command.rankstatsxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, p.getName());
}
}
if (vars.length == 2) {
if (Util.isPositive(vars[1]) || vars[1].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase("add") && (Bankcraft.perms.has(p, "bankcraft.admin"))) {
Block signblock = p.getTargetBlock(null, 50);
if (signblock.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) signblock.getState();
if (sign.getLine(0).contains("[Bank]")) {
Integer typsign = -1;
try {
typsign = bankcraft.getSignDatabaseInterface().getType(signblock.getX(), signblock.getY(), signblock.getZ(), signblock.getWorld());
} catch (Exception e) {
e.printStackTrace();
}
if (typsign == 1 || typsign == 2 || typsign == 3 || typsign == 4 || typsign == 6 || typsign == 7 || typsign == 8 || typsign == 9 || typsign == 12 || typsign == 13 || typsign == 14 || typsign == 15) {
Integer x = signblock.getX();
Integer y = signblock.getY();
Integer z = signblock.getZ();
World w = signblock.getWorld();
Integer newType;
Integer currentType = bankcraft.getSignDatabaseInterface().getType(x, y, z, w);
if (currentType == 1 || currentType == 2 || currentType == 6 || currentType == 7|| currentType == 12|| currentType == 13) {
newType = currentType +2;
bankcraft.getSignDatabaseInterface().changeType(x, y, z, newType, w);
}
bankcraft.getSignDatabaseInterface().addAmount(x, y, z, w, vars[1]);
coHa.printMessage(p, "message.amountAddedSuccessfullyToSign", vars[1], p.getName());
bankcraft.getSignHandler().updateSign(signblock,0);
return true;
}
}
}
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], "", p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.deposit")) && (Bankcraft.perms.has(p, "bankcraft.command.deposit") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdraw")) && (Bankcraft.perms.has(p, "bankcraft.command.withdraw") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.depositxp")) && (Bankcraft.perms.has(p, "bankcraft.command.depositxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.withdrawxp")) && (Bankcraft.perms.has(p, "bankcraft.command.withdrawxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchange")) && (Bankcraft.perms.has(p, "bankcraft.command.exchange") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.exchangexp")) && (Bankcraft.perms.has(p, "bankcraft.command.exchangexp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], vars[1], p, p.getName());
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balance")) && (Bankcraft.perms.has(p, "bankcraft.command.balance.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
else if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.balancexp")) && (Bankcraft.perms.has(p, "bankcraft.command.balancexp.other") || Bankcraft.perms.has(p, "bankcraft.command"))) {
return bankcraft.getInteractionHandler().interact(vars[0], null, p, vars[1]);
}
}
}
if (vars.length == 3) {
if (Util.isPositive(vars[2]) || vars[2].equalsIgnoreCase("all")) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transfer")) && (Bankcraft.perms.has(p, "bankcraft.command.transfer") || Bankcraft.perms.has(p, "bankcraft.command"))) {
double amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getMoneyDatabaseInterface().getBalance(p.getName());
} else {
amount = Double.parseDouble(vars[2]);
}
((MoneyBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.transferxp")) && (Bankcraft.perms.has(p, "bankcraft.command.transferxp") || Bankcraft.perms.has(p, "bankcraft.command"))) {
int amount;
if (vars[2].equalsIgnoreCase("all")) {
amount = bankcraft.getExperienceDatabaseInterface().getBalance(p.getName());
} else {
amount = Integer.parseInt(vars[2]);
}
((ExperienceBankingHandler)bankcraft.getBankingHandlers()[0]).transferFromAccountToAccount(p.getName(), vars[1], amount,p);
return true;
}
}
}
} else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
return true;
}
} else {
if (cmdlabel.equalsIgnoreCase("bankadmin") || cmdlabel.equalsIgnoreCase("bcadmin")) {
if (vars.length == 0) {
sendAdminHelp(p);
return true;
}
else if (vars.length == 1) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.help"))) {
sendAdminHelp(p);
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.reloadconfig")) && (Bankcraft.perms.has(p, "bankcraft.command.reloadconfig") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.reloadConfig();
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Config reloaded!");
return true;
}
}
else if (vars.length == 2) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clear")) && (Bankcraft.perms.has(p, "bankcraft.command.clear") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], 0D);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account cleared!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.clearxp")) && (Bankcraft.perms.has(p, "bankcraft.command.clearxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], 0);
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account cleared!");
return true;
}
}
else if (vars.length == 3) {
if (Util.isDouble(vars[2])) {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.set")) && (Bankcraft.perms.has(p, "bankcraft.command.set") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().setBalance(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.setxp")) && (Bankcraft.perms.has(p, "bankcraft.command.setxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().setBalance(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "XP-Account set!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grant")) && (Bankcraft.perms.has(p, "bankcraft.command.grant") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getMoneyDatabaseInterface().addToAccount(vars[1], Double.parseDouble(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Money to "+vars[1]+"!");
return true;
}
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.grantxp")) && (Bankcraft.perms.has(p, "bankcraft.command.grantxp") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
bankcraft.getExperienceDatabaseInterface().addToAccount(vars[1], Integer.parseInt(vars[2]));
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Granted "+vars[2]+" Experience to "+vars[1]+"!");
return true;
}
} else {
if (vars[0].equalsIgnoreCase(coHa.getString("signAndCommand.admin.databaseimport")) && (Bankcraft.perms.has(p, "bankcraft.command.databaseimport") || Bankcraft.perms.has(p, "bankcraft.command.admin"))) {
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing...");
DatabaseManagerInterface loadDataMan = null;
AccountDatabaseInterface <Double> loadDataMoney = null;
AccountDatabaseInterface <Integer> loadDataXp = null;
SignDatabaseInterface loadDataSign = null;
DatabaseManagerInterface saveDataMan = null;
AccountDatabaseInterface <Double> saveDataMoney = null;
AccountDatabaseInterface <Integer> saveDataXp = null;
SignDatabaseInterface saveDataSign = null;
if (vars[1].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from flatfile...");
loadDataMan = new DatabaseManagerFlatFile(bankcraft);
loadDataMoney = new MoneyFlatFileInterface(bankcraft);
loadDataXp = new ExperienceFlatFileInterface(bankcraft);
loadDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[1].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Importing from mysql...");
loadDataMan = new DatabaseManagerMysql(bankcraft);
loadDataMoney = new MoneyMysqlInterface(bankcraft);
loadDataXp = new ExperienceMysqlInterface(bankcraft);
loadDataSign = new SignMysqlInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("flatfile")) {
//Load flatFile
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to flatfile...");
saveDataMan = new DatabaseManagerFlatFile(bankcraft);
saveDataMoney = new MoneyFlatFileInterface(bankcraft);
saveDataXp = new ExperienceFlatFileInterface(bankcraft);
saveDataSign = new SignFlatFileInterface(bankcraft);
}
if (vars[2].equalsIgnoreCase("mysql")) {
//Load mysql
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Exporting to mysql...");
saveDataMan = new DatabaseManagerMysql(bankcraft);
saveDataMoney = new MoneyMysqlInterface(bankcraft);
saveDataXp = new ExperienceMysqlInterface(bankcraft);
saveDataSign = new SignMysqlInterface(bankcraft);
}
//get them ready
loadDataMan.setupDatabase();
saveDataMan.setupDatabase();
//move money data
for (String accountName: loadDataMoney.getAccounts()) {
saveDataMoney.setBalance(accountName, loadDataMoney.getBalance(accountName));
}
//move xp data
for (String accountName: loadDataXp.getAccounts()) {
saveDataXp.setBalance(accountName, loadDataXp.getBalance(accountName));
}
//move sign data
String amounts;
String[] amountsArray;
int type;
for (Location location: loadDataSign.getLocations(-1, null)) {
//Get amounts
amountsArray = loadDataSign.getAmounts((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
amounts = amountsArray[0];
for (int i = 1; i< amountsArray.length; i++) {
amounts+=":"+amountsArray[i];
}
//Get type
type = loadDataSign.getType((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld());
//Create new sign in save database
saveDataSign.createNewSign((int)location.getX(), (int)location.getY(), (int)location.getZ(), location.getWorld(), type, amounts);
}
//close databases
loadDataMan.closeDatabase();
saveDataMan.closeDatabase();
//Send success message
p.sendMessage(coHa.getString("chat.color") + coHa.getString("chat.prefix") + "Moved all data from "+vars[1]+" to "+vars[2]+"!");
return true;
}
}
}
else {
p.sendMessage(ChatColor.RED + coHa.getString("chat.prefix") + "Wrong Syntax or missing permissions! Please see /bank help for more information!");
}
return true;
}
}
} else {
Bankcraft.log.info("[Bankcraft] Please use this ingame!");
}
return false;
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
index e09b4dd8188..e815157cfa7 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java
@@ -1,312 +1,312 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.metadata;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.ProcessedClusterStateUpdateTask;
import org.elasticsearch.cluster.action.index.NodeIndexCreatedAction;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.strategy.ShardsRoutingStrategy;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Maps;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.timer.Timeout;
import org.elasticsearch.common.timer.TimerTask;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.indices.InvalidIndexNameException;
import org.elasticsearch.timer.TimerService;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
import static org.elasticsearch.common.settings.ImmutableSettings.*;
/**
* @author kimchy (shay.banon)
*/
public class MetaDataCreateIndexService extends AbstractComponent {
private final Environment environment;
private final TimerService timerService;
private final ClusterService clusterService;
private final ShardsRoutingStrategy shardsRoutingStrategy;
private final NodeIndexCreatedAction nodeIndexCreatedAction;
@Inject public MetaDataCreateIndexService(Settings settings, Environment environment, TimerService timerService, ClusterService clusterService, ShardsRoutingStrategy shardsRoutingStrategy,
NodeIndexCreatedAction nodeIndexCreatedAction) {
super(settings);
this.environment = environment;
this.timerService = timerService;
this.clusterService = clusterService;
this.shardsRoutingStrategy = shardsRoutingStrategy;
this.nodeIndexCreatedAction = nodeIndexCreatedAction;
}
public void createIndex(final Request request, final Listener userListener) {
clusterService.submitStateUpdateTask("create-index [" + request.index + "], cause [" + request.cause + "]", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
final CreateIndexListener listener = new CreateIndexListener(request, userListener);
try {
if (currentState.routingTable().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (currentState.metaData().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (request.index.contains(" ")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain whitespace"));
return currentState;
}
if (request.index.contains(",")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain ',"));
return currentState;
}
if (request.index.contains("#")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain '#"));
return currentState;
}
if (request.index.charAt(0) == '_') {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not start with '_'"));
return currentState;
}
if (!request.index.toLowerCase().equals(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must be lowercase"));
return currentState;
}
if (!Strings.validFileName(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS));
return currentState;
}
if (currentState.metaData().aliases().contains(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "an alias with the same name already exists"));
return currentState;
}
// add to the mappings files that exists within the config/mappings location
Map<String, String> mappings = Maps.newHashMap();
File mappingsDir = new File(environment.configFile(), "mappings");
if (mappingsDir.exists() && mappingsDir.isDirectory()) {
File defaultMappingsDir = new File(mappingsDir, "_default");
- if (mappingsDir.exists() && mappingsDir.isDirectory()) {
+ if (defaultMappingsDir.exists() && defaultMappingsDir.isDirectory()) {
addMappings(mappings, defaultMappingsDir);
}
File indexMappingsDir = new File(mappingsDir, request.index);
- if (mappingsDir.exists() && mappingsDir.isDirectory()) {
+ if (indexMappingsDir.exists() && indexMappingsDir.isDirectory()) {
addMappings(mappings, indexMappingsDir);
}
}
// TODO add basic mapping validation
// put this last so index level mappings can override default mappings
mappings.putAll(request.mappings);
ImmutableSettings.Builder indexSettingsBuilder = settingsBuilder().put(request.settings);
if (request.settings.get(SETTING_NUMBER_OF_SHARDS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
}
if (request.settings.get(SETTING_NUMBER_OF_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
}
Settings actualIndexSettings = indexSettingsBuilder.build();
IndexMetaData.Builder indexMetaData = newIndexMetaDataBuilder(request.index).settings(actualIndexSettings);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
indexMetaData.putMapping(entry.getKey(), entry.getValue());
}
MetaData newMetaData = newMetaDataBuilder()
.metaData(currentState.metaData())
.put(indexMetaData)
.build();
logger.info("[{}] creating index, cause [{}], shards [{}]/[{}], mappings {}", request.index, request.cause, indexMetaData.numberOfShards(), indexMetaData.numberOfReplicas(), mappings.keySet());
final AtomicInteger counter = new AtomicInteger(currentState.nodes().size());
final NodeIndexCreatedAction.Listener nodeIndexCreateListener = new NodeIndexCreatedAction.Listener() {
@Override public void onNodeIndexCreated(String index, String nodeId) {
if (index.equals(request.index)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new Response(true));
nodeIndexCreatedAction.remove(this);
}
}
}
};
nodeIndexCreatedAction.add(nodeIndexCreateListener);
Timeout timeoutTask = timerService.newTimeout(new TimerTask() {
@Override public void run(Timeout timeout) throws Exception {
listener.onResponse(new Response(false));
nodeIndexCreatedAction.remove(nodeIndexCreateListener);
}
}, request.timeout, TimerService.ExecutionType.THREADED);
listener.timeout = timeoutTask;
return newClusterStateBuilder().state(currentState).metaData(newMetaData).build();
} catch (Exception e) {
listener.onFailure(e);
return currentState;
}
}
});
}
private void addMappings(Map<String, String> mappings, File mappingsDir) {
File[] mappingsFiles = mappingsDir.listFiles();
for (File mappingFile : mappingsFiles) {
String fileNameNoSuffix = mappingFile.getName().substring(0, mappingFile.getName().lastIndexOf('.'));
if (mappings.containsKey(fileNameNoSuffix)) {
// if we have the mapping defined, ignore it
continue;
}
try {
mappings.put(fileNameNoSuffix, Streams.copyToString(new FileReader(mappingFile)));
} catch (IOException e) {
logger.warn("failed to read mapping [" + fileNameNoSuffix + "] from location [" + mappingFile + "], ignoring...", e);
}
}
}
class CreateIndexListener implements Listener {
private AtomicBoolean notified = new AtomicBoolean();
private final Request request;
private final Listener listener;
volatile Timeout timeout;
private CreateIndexListener(Request request, Listener listener) {
this.request = request;
this.listener = listener;
}
@Override public void onResponse(final Response response) {
if (notified.compareAndSet(false, true)) {
if (timeout != null) {
timeout.cancel();
}
// do the reroute after indices have been created on all the other nodes so we can query them for some info (like shard allocation)
clusterService.submitStateUpdateTask("reroute after index [" + request.index + "] creation", new ProcessedClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
RoutingTable.Builder routingTableBuilder = new RoutingTable.Builder();
for (IndexRoutingTable indexRoutingTable : currentState.routingTable().indicesRouting().values()) {
routingTableBuilder.add(indexRoutingTable);
}
IndexRoutingTable.Builder indexRoutingBuilder = new IndexRoutingTable.Builder(request.index)
.initializeEmpty(currentState.metaData().index(request.index));
routingTableBuilder.add(indexRoutingBuilder);
RoutingTable newRoutingTable = shardsRoutingStrategy.reroute(newClusterStateBuilder().state(currentState).routingTable(routingTableBuilder).build());
return newClusterStateBuilder().state(currentState).routingTable(newRoutingTable).build();
}
@Override public void clusterStateProcessed(ClusterState clusterState) {
listener.onResponse(response);
}
});
}
}
@Override public void onFailure(Throwable t) {
if (notified.compareAndSet(false, true)) {
if (timeout != null) {
timeout.cancel();
}
listener.onFailure(t);
}
}
}
public static interface Listener {
void onResponse(Response response);
void onFailure(Throwable t);
}
public static class Request {
final String cause;
final String index;
Settings settings = ImmutableSettings.Builder.EMPTY_SETTINGS;
Map<String, String> mappings = Maps.newHashMap();
TimeValue timeout = TimeValue.timeValueSeconds(5);
public Request(String cause, String index) {
this.cause = cause;
this.index = index;
}
public Request settings(Settings settings) {
this.settings = settings;
return this;
}
public Request mappings(Map<String, String> mappings) {
this.mappings.putAll(mappings);
return this;
}
public Request timeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
}
public static class Response {
private final boolean acknowledged;
public Response(boolean acknowledged) {
this.acknowledged = acknowledged;
}
public boolean acknowledged() {
return acknowledged;
}
}
}
| false | true | public void createIndex(final Request request, final Listener userListener) {
clusterService.submitStateUpdateTask("create-index [" + request.index + "], cause [" + request.cause + "]", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
final CreateIndexListener listener = new CreateIndexListener(request, userListener);
try {
if (currentState.routingTable().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (currentState.metaData().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (request.index.contains(" ")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain whitespace"));
return currentState;
}
if (request.index.contains(",")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain ',"));
return currentState;
}
if (request.index.contains("#")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain '#"));
return currentState;
}
if (request.index.charAt(0) == '_') {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not start with '_'"));
return currentState;
}
if (!request.index.toLowerCase().equals(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must be lowercase"));
return currentState;
}
if (!Strings.validFileName(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS));
return currentState;
}
if (currentState.metaData().aliases().contains(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "an alias with the same name already exists"));
return currentState;
}
// add to the mappings files that exists within the config/mappings location
Map<String, String> mappings = Maps.newHashMap();
File mappingsDir = new File(environment.configFile(), "mappings");
if (mappingsDir.exists() && mappingsDir.isDirectory()) {
File defaultMappingsDir = new File(mappingsDir, "_default");
if (mappingsDir.exists() && mappingsDir.isDirectory()) {
addMappings(mappings, defaultMappingsDir);
}
File indexMappingsDir = new File(mappingsDir, request.index);
if (mappingsDir.exists() && mappingsDir.isDirectory()) {
addMappings(mappings, indexMappingsDir);
}
}
// TODO add basic mapping validation
// put this last so index level mappings can override default mappings
mappings.putAll(request.mappings);
ImmutableSettings.Builder indexSettingsBuilder = settingsBuilder().put(request.settings);
if (request.settings.get(SETTING_NUMBER_OF_SHARDS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
}
if (request.settings.get(SETTING_NUMBER_OF_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
}
Settings actualIndexSettings = indexSettingsBuilder.build();
IndexMetaData.Builder indexMetaData = newIndexMetaDataBuilder(request.index).settings(actualIndexSettings);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
indexMetaData.putMapping(entry.getKey(), entry.getValue());
}
MetaData newMetaData = newMetaDataBuilder()
.metaData(currentState.metaData())
.put(indexMetaData)
.build();
logger.info("[{}] creating index, cause [{}], shards [{}]/[{}], mappings {}", request.index, request.cause, indexMetaData.numberOfShards(), indexMetaData.numberOfReplicas(), mappings.keySet());
final AtomicInteger counter = new AtomicInteger(currentState.nodes().size());
final NodeIndexCreatedAction.Listener nodeIndexCreateListener = new NodeIndexCreatedAction.Listener() {
@Override public void onNodeIndexCreated(String index, String nodeId) {
if (index.equals(request.index)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new Response(true));
nodeIndexCreatedAction.remove(this);
}
}
}
};
nodeIndexCreatedAction.add(nodeIndexCreateListener);
Timeout timeoutTask = timerService.newTimeout(new TimerTask() {
@Override public void run(Timeout timeout) throws Exception {
listener.onResponse(new Response(false));
nodeIndexCreatedAction.remove(nodeIndexCreateListener);
}
}, request.timeout, TimerService.ExecutionType.THREADED);
listener.timeout = timeoutTask;
return newClusterStateBuilder().state(currentState).metaData(newMetaData).build();
} catch (Exception e) {
listener.onFailure(e);
return currentState;
}
}
});
}
| public void createIndex(final Request request, final Listener userListener) {
clusterService.submitStateUpdateTask("create-index [" + request.index + "], cause [" + request.cause + "]", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
final CreateIndexListener listener = new CreateIndexListener(request, userListener);
try {
if (currentState.routingTable().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (currentState.metaData().hasIndex(request.index)) {
listener.onFailure(new IndexAlreadyExistsException(new Index(request.index)));
return currentState;
}
if (request.index.contains(" ")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain whitespace"));
return currentState;
}
if (request.index.contains(",")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain ',"));
return currentState;
}
if (request.index.contains("#")) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain '#"));
return currentState;
}
if (request.index.charAt(0) == '_') {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not start with '_'"));
return currentState;
}
if (!request.index.toLowerCase().equals(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must be lowercase"));
return currentState;
}
if (!Strings.validFileName(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS));
return currentState;
}
if (currentState.metaData().aliases().contains(request.index)) {
listener.onFailure(new InvalidIndexNameException(new Index(request.index), request.index, "an alias with the same name already exists"));
return currentState;
}
// add to the mappings files that exists within the config/mappings location
Map<String, String> mappings = Maps.newHashMap();
File mappingsDir = new File(environment.configFile(), "mappings");
if (mappingsDir.exists() && mappingsDir.isDirectory()) {
File defaultMappingsDir = new File(mappingsDir, "_default");
if (defaultMappingsDir.exists() && defaultMappingsDir.isDirectory()) {
addMappings(mappings, defaultMappingsDir);
}
File indexMappingsDir = new File(mappingsDir, request.index);
if (indexMappingsDir.exists() && indexMappingsDir.isDirectory()) {
addMappings(mappings, indexMappingsDir);
}
}
// TODO add basic mapping validation
// put this last so index level mappings can override default mappings
mappings.putAll(request.mappings);
ImmutableSettings.Builder indexSettingsBuilder = settingsBuilder().put(request.settings);
if (request.settings.get(SETTING_NUMBER_OF_SHARDS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
}
if (request.settings.get(SETTING_NUMBER_OF_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
}
Settings actualIndexSettings = indexSettingsBuilder.build();
IndexMetaData.Builder indexMetaData = newIndexMetaDataBuilder(request.index).settings(actualIndexSettings);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
indexMetaData.putMapping(entry.getKey(), entry.getValue());
}
MetaData newMetaData = newMetaDataBuilder()
.metaData(currentState.metaData())
.put(indexMetaData)
.build();
logger.info("[{}] creating index, cause [{}], shards [{}]/[{}], mappings {}", request.index, request.cause, indexMetaData.numberOfShards(), indexMetaData.numberOfReplicas(), mappings.keySet());
final AtomicInteger counter = new AtomicInteger(currentState.nodes().size());
final NodeIndexCreatedAction.Listener nodeIndexCreateListener = new NodeIndexCreatedAction.Listener() {
@Override public void onNodeIndexCreated(String index, String nodeId) {
if (index.equals(request.index)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new Response(true));
nodeIndexCreatedAction.remove(this);
}
}
}
};
nodeIndexCreatedAction.add(nodeIndexCreateListener);
Timeout timeoutTask = timerService.newTimeout(new TimerTask() {
@Override public void run(Timeout timeout) throws Exception {
listener.onResponse(new Response(false));
nodeIndexCreatedAction.remove(nodeIndexCreateListener);
}
}, request.timeout, TimerService.ExecutionType.THREADED);
listener.timeout = timeoutTask;
return newClusterStateBuilder().state(currentState).metaData(newMetaData).build();
} catch (Exception e) {
listener.onFailure(e);
return currentState;
}
}
});
}
|
diff --git a/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java b/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
index a92d28bf0..d177ee6d8 100644
--- a/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
+++ b/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
@@ -1,590 +1,590 @@
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2006 The Eigenbase Project
// Copyright (C) 2002-2006 Disruptive Tech
// Copyright (C) 2005-2006 LucidEra, Inc.
// Portions Copyright (C) 2003-2006 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.eigenbase.oj.rel;
import java.util.*;
import java.util.List;
import java.util.logging.*;
import openjava.mop.*;
import openjava.ptree.*;
import org.eigenbase.oj.rex.*;
import org.eigenbase.oj.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.rel.metadata.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
import org.eigenbase.runtime.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.trace.*;
import org.eigenbase.util.*;
/**
* <code>IterCalcRel</code> is an iterator implementation of a combination of
* {@link ProjectRel} above an optional {@link FilterRel}. It takes a {@link
* TupleIter iterator} as input, and for each row applies the filter condition
* if defined. Rows passing the filter expression are transformed via projection
* and returned. Note that the same object is always returned (with different
* values), so parents must not buffer the result.
*
* <p>Rules:
*
* <ul>
* <li>{@link org.eigenbase.oj.rel.IterRules.IterCalcRule} creates an
* IterCalcRel from a {@link org.eigenbase.rel.CalcRel}</li>
* </ul>
*/
public class IterCalcRel
extends SingleRel
implements JavaRel
{
//~ Static fields/initializers ---------------------------------------------
private static boolean abortOnError = true;
private static boolean errorBuffering = false;
//~ Instance fields --------------------------------------------------------
private final RexProgram program;
/**
* Values defined in {@link ProjectRelBase.Flags}.
*/
protected int flags;
private String tag;
//~ Constructors -----------------------------------------------------------
public IterCalcRel(
RelOptCluster cluster,
RelNode child,
RexProgram program,
int flags)
{
this(cluster, child, program, flags, null);
}
public IterCalcRel(
RelOptCluster cluster,
RelNode child,
RexProgram program,
int flags,
String tag)
{
super(
cluster,
new RelTraitSet(CallingConvention.ITERATOR),
child);
this.flags = flags;
this.program = program;
this.rowType = program.getOutputRowType();
this.tag = tag;
}
//~ Methods ----------------------------------------------------------------
// TODO jvs 10-May-2004: need a computeSelfCost which takes condition into
// account; maybe inherit from CalcRelBase?
public void explain(RelOptPlanWriter pw)
{
program.explainCalc(this, pw);
}
protected String computeDigest()
{
String tempDigest = super.computeDigest();
if (tag != null) {
// append logger type to digest
int lastParen = tempDigest.lastIndexOf(')');
tempDigest =
tempDigest.substring(0, lastParen)
+ ",type=" + tag
+ tempDigest.substring(lastParen);
}
return tempDigest;
}
public double getRows()
{
return
FilterRel.estimateFilteredRows(
getChild(),
program.getCondition());
}
public RelOptCost computeSelfCost(RelOptPlanner planner)
{
double dRows = RelMetadataQuery.getRowCount(this);
double dCpu =
RelMetadataQuery.getRowCount(getChild())
* program.getExprCount();
double dIo = 0;
return planner.makeCost(dRows, dCpu, dIo);
}
public Object clone()
{
IterCalcRel clone =
new IterCalcRel(
getCluster(),
RelOptUtil.clone(getChild()),
program.copy(),
getFlags(),
tag);
clone.inheritTraitsFrom(this);
return clone;
}
public int getFlags()
{
return flags;
}
public boolean isBoxed()
{
return
(flags & ProjectRelBase.Flags.Boxed) == ProjectRelBase.Flags.Boxed;
}
/**
* Burrows into a synthetic record and returns the underlying relation which
* provides the field called <code>fieldName</code>.
*/
public JavaRel implementFieldAccess(
JavaRelImplementor implementor,
String fieldName)
{
if (!isBoxed()) {
return
implementor.implementFieldAccess((JavaRel) getChild(),
fieldName);
}
RelDataType type = getRowType();
int field = type.getFieldOrdinal(fieldName);
RexLocalRef ref = program.getProjectList().get(field);
final int index = ref.getIndex();
return
implementor.findRel(
(JavaRel) this,
program.getExprList().get(index));
}
/**
* Disables throwing of exceptions on error. Do not set this false without a
* very good reason! Doing so will prevent type cast, overflow/underflow,
* etc. errors in Farrago.
*/
public static void setAbortOnError(boolean abortOnError)
{
IterCalcRel.abortOnError = abortOnError;
}
/**
* Allows errors to be buffered, in the event that they overflow the
* error handler.
*
* @param errorBuffering whether to buffer errors
*/
public static void setErrorBuffering(boolean errorBuffering)
{
IterCalcRel.errorBuffering = errorBuffering;
}
public static Expression implementAbstract(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
return
implementAbstractTupleIter(
implementor,
rel,
childExp,
varInputRow,
inputRowType,
outputRowType,
program,
tag);
}
/**
* Generates code for a Java expression satisfying the
* {@link org.eigenbase.runtime.TupleIter} interface. The generated
* code allocates a {@link org.eigenbase.runtime.CalcTupleIter}
* with a dynamic {@link org.eigenbase.runtime.TupleIter#fetchNext()}
* method. If the "abort on error" flag is false, or an error handling
* tag is specified, then fetchNext is written to handle row errors.
*
* <p>
*
* Row errors are handled by wrapping expressions that can fail
* with a try/catch block. A caught RuntimeException is then published
* to an "connection variable." In the event that errors can overflow,
* an "error buffering" flag allows them to be posted again on the next
* iteration of fetchNext.
*
* @param implementor an object that implements relations as Java code
* @param rel the relation to be implemented
* @param childExp the implemented child of the relation
* @param varInputRow the Java variable to use for the input row
* @param inputRowType the rel data type of the input row
* @param outputRowType the rel data type of the output row
* @param program the rex program to implemented by the relation
* @param tag an error handling tag
* @return a Java expression satisfying the TupleIter interface
*/
public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
- boolean errorRecovery = (abortOnError == false || tag != null);
+ boolean errorRecovery = !abortOnError || tag != null;
// Error buffering should not be enabled unless error recovery is
- assert (errorBuffering == false || errorRecovery == true);
+ assert !errorBuffering || errorRecovery;
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
- if (errorRecovery && backwardsCompatible == false) {
+ if (errorRecovery && !backwardsCompatible) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
- if (errorRecovery == false) {
+ if (!errorRecovery) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
- whileBody.add(
+ calcStmts.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
- if (errorRecovery && backwardsCompatible == false) {
+ if (errorRecovery && !backwardsCompatible) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
public ParseTree implement(JavaRelImplementor implementor)
{
Expression childExp =
implementor.visitJavaChild(this, 0, (JavaRel) getChild());
RelDataType outputRowType = getRowType();
RelDataType inputRowType = getChild().getRowType();
Variable varInputRow = implementor.newVariable();
implementor.bind(
getChild(),
varInputRow);
return
implementAbstract(
implementor,
this,
childExp,
varInputRow,
inputRowType,
outputRowType,
program,
tag);
}
public RexProgram getProgram()
{
return program;
}
public String getTag()
{
return tag;
}
private static Statement declareInputRow(
OJClass inputRowClass, Variable varInputRow, Variable varInputObj)
{
return new VariableDeclaration(
TypeName.forOJClass(inputRowClass),
varInputRow.toString(),
new CastExpression(
TypeName.forOJClass(inputRowClass),
varInputObj));
}
}
// End IterCalcRel.java
| false | true | public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
boolean errorRecovery = (abortOnError == false || tag != null);
// Error buffering should not be enabled unless error recovery is
assert (errorBuffering == false || errorRecovery == true);
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
if (errorRecovery && backwardsCompatible == false) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
if (errorRecovery == false) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
if (errorRecovery && backwardsCompatible == false) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
| public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
boolean errorRecovery = !abortOnError || tag != null;
// Error buffering should not be enabled unless error recovery is
assert !errorBuffering || errorRecovery;
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
if (errorRecovery && !backwardsCompatible) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
if (!errorRecovery) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
calcStmts.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
if (errorRecovery && !backwardsCompatible) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
|
diff --git a/core/src/main/java/org/chromattic/core/bean/PropertyInfo.java b/core/src/main/java/org/chromattic/core/bean/PropertyInfo.java
index b4e45b16..859ceb79 100644
--- a/core/src/main/java/org/chromattic/core/bean/PropertyInfo.java
+++ b/core/src/main/java/org/chromattic/core/bean/PropertyInfo.java
@@ -1,110 +1,111 @@
/*
* Copyright (C) 2003-2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.chromattic.core.bean;
import org.reflext.api.MethodInfo;
import org.reflext.api.AnnotationIntrospector;
import org.chromattic.core.bean.AccessMode;
import java.lang.annotation.Annotation;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
* @version $Revision$
*/
public abstract class PropertyInfo {
/** . */
private final String name;
/** . */
private final MethodInfo getter;
/** . */
private final MethodInfo setter;
public PropertyInfo(String name, MethodInfo getter, MethodInfo setter) {
this.name = name;
this.getter = getter;
this.setter = setter;
}
public String getName() {
return name;
}
public AccessMode getAccessMode() {
if (getter == null) {
if (setter == null) {
throw new AssertionError("wtf");
} else {
return AccessMode.WRITE_ONLY;
}
} else {
if (setter == null) {
return AccessMode.READ_ONLY;
} else {
return AccessMode.READ_WRITE;
}
}
}
public MethodInfo getGetter() {
return getter;
}
public MethodInfo getSetter() {
return setter;
}
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException();
}
//
A annotation = null;
//
if (getter != null) {
annotation = new AnnotationIntrospector<A>(annotationClass).resolve(getter);
}
//
if (setter != null) {
A setterAnnotation = new AnnotationIntrospector<A>(annotationClass).resolve(setter);
if (setterAnnotation != null) {
if (annotation != null) {
- throw new IllegalStateException();
+ throw new IllegalStateException("The same annotation " + annotation + " is present on a getter " +
+ getter + " and setter" + setter);
}
annotation = setterAnnotation;
}
}
//
return annotation;
}
@Override
public String toString() {
return "Property[name=" + name + "]";
}
}
| true | true | public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException();
}
//
A annotation = null;
//
if (getter != null) {
annotation = new AnnotationIntrospector<A>(annotationClass).resolve(getter);
}
//
if (setter != null) {
A setterAnnotation = new AnnotationIntrospector<A>(annotationClass).resolve(setter);
if (setterAnnotation != null) {
if (annotation != null) {
throw new IllegalStateException();
}
annotation = setterAnnotation;
}
}
//
return annotation;
}
| public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException();
}
//
A annotation = null;
//
if (getter != null) {
annotation = new AnnotationIntrospector<A>(annotationClass).resolve(getter);
}
//
if (setter != null) {
A setterAnnotation = new AnnotationIntrospector<A>(annotationClass).resolve(setter);
if (setterAnnotation != null) {
if (annotation != null) {
throw new IllegalStateException("The same annotation " + annotation + " is present on a getter " +
getter + " and setter" + setter);
}
annotation = setterAnnotation;
}
}
//
return annotation;
}
|
diff --git a/app/src/com/blogspot/fwfaill/lunchbuddy/CourseCursorAdapter.java b/app/src/com/blogspot/fwfaill/lunchbuddy/CourseCursorAdapter.java
index 633d7f2..fb3f56c 100644
--- a/app/src/com/blogspot/fwfaill/lunchbuddy/CourseCursorAdapter.java
+++ b/app/src/com/blogspot/fwfaill/lunchbuddy/CourseCursorAdapter.java
@@ -1,78 +1,78 @@
/*
* Copyright 2012 Aleksi Niiranen
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blogspot.fwfaill.lunchbuddy;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.View;
import android.widget.TextView;
public class CourseCursorAdapter extends ResourceCursorAdapter {
private static final String TAG = "CourseCursorAdapter";
private String mLang;
private int mColumnIndexTitleFi;
private int mColumnIndexTitleEn;
private int mColumnIndexTitleSe;
private int mColumnIndexTitlePrice;
private int mColumnIndexTitleProperties;
public CourseCursorAdapter(int layout, Context context, Cursor c) {
super(context, layout, c);
mColumnIndexTitleFi = c.getColumnIndexOrThrow(LunchBuddy.Courses.COLUMN_NAME_TITLE_FI);
mColumnIndexTitleEn = c.getColumnIndexOrThrow(LunchBuddy.Courses.COLUMN_NAME_TITLE_EN);
mColumnIndexTitleSe = c.getColumnIndexOrThrow(LunchBuddy.Courses.COLUMN_NAME_TITLE_SE);
mColumnIndexTitlePrice = c.getColumnIndexOrThrow(LunchBuddy.Courses.COLUMN_NAME_PRICE);
mColumnIndexTitleProperties = c.getColumnIndexOrThrow(LunchBuddy.Courses.COLUMN_NAME_PROPERTIES);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
mLang = preferences.getString("language_preference", context.getString(R.string.default_language));
}
@Override
public void bindView(View view, Context context, Cursor c) {
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.course_title);
holder.price = (TextView) view.findViewById(R.id.course_price);
holder.properties = (TextView) view.findViewById(R.id.course_properties);
view.setTag(holder);
}
- if (mLang.equals("fi") || c.getString(mColumnIndexTitleSe).equals("null") || c.getString(mColumnIndexTitleEn).equals("null"))
- holder.title.setText(c.getString(mColumnIndexTitleFi));
- else if (mLang.equals("se"))
+ if (mLang.equals("en") && !c.getString(mColumnIndexTitleEn).equals("null"))
+ holder.title.setText(c.getString(mColumnIndexTitleEn));
+ else if (mLang.equals("se") && !c.getString(mColumnIndexTitleSe).equals("null"))
holder.title.setText(c.getString(mColumnIndexTitleSe));
else
- holder.title.setText(c.getString(mColumnIndexTitleEn));
+ holder.title.setText(c.getString(mColumnIndexTitleFi));
holder.price.setText(c.getString(mColumnIndexTitlePrice) + " €");
String properties = c.getString(mColumnIndexTitleProperties).equals("null") ? "" : c.getString(mColumnIndexTitleProperties);
holder.properties.setText(properties);
}
static class ViewHolder {
public TextView title;
public TextView price;
public TextView properties;
}
}
| false | true | public void bindView(View view, Context context, Cursor c) {
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.course_title);
holder.price = (TextView) view.findViewById(R.id.course_price);
holder.properties = (TextView) view.findViewById(R.id.course_properties);
view.setTag(holder);
}
if (mLang.equals("fi") || c.getString(mColumnIndexTitleSe).equals("null") || c.getString(mColumnIndexTitleEn).equals("null"))
holder.title.setText(c.getString(mColumnIndexTitleFi));
else if (mLang.equals("se"))
holder.title.setText(c.getString(mColumnIndexTitleSe));
else
holder.title.setText(c.getString(mColumnIndexTitleEn));
holder.price.setText(c.getString(mColumnIndexTitlePrice) + " €");
String properties = c.getString(mColumnIndexTitleProperties).equals("null") ? "" : c.getString(mColumnIndexTitleProperties);
holder.properties.setText(properties);
}
| public void bindView(View view, Context context, Cursor c) {
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.course_title);
holder.price = (TextView) view.findViewById(R.id.course_price);
holder.properties = (TextView) view.findViewById(R.id.course_properties);
view.setTag(holder);
}
if (mLang.equals("en") && !c.getString(mColumnIndexTitleEn).equals("null"))
holder.title.setText(c.getString(mColumnIndexTitleEn));
else if (mLang.equals("se") && !c.getString(mColumnIndexTitleSe).equals("null"))
holder.title.setText(c.getString(mColumnIndexTitleSe));
else
holder.title.setText(c.getString(mColumnIndexTitleFi));
holder.price.setText(c.getString(mColumnIndexTitlePrice) + " €");
String properties = c.getString(mColumnIndexTitleProperties).equals("null") ? "" : c.getString(mColumnIndexTitleProperties);
holder.properties.setText(properties);
}
|
diff --git a/ardor3d-jogl/src/main/java/com/ardor3d/scene/state/jogl/JoglTextureStateUtil.java b/ardor3d-jogl/src/main/java/com/ardor3d/scene/state/jogl/JoglTextureStateUtil.java
index d6f281b..9822c6e 100644
--- a/ardor3d-jogl/src/main/java/com/ardor3d/scene/state/jogl/JoglTextureStateUtil.java
+++ b/ardor3d-jogl/src/main/java/com/ardor3d/scene/state/jogl/JoglTextureStateUtil.java
@@ -1,1699 +1,1699 @@
/**
* Copyright (c) 2008-2009 Ardor Labs, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <http://www.ardor3d.com/LICENSE>.
*/
package com.ardor3d.scene.state.jogl;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.logging.Logger;
import javax.media.opengl.GL;
import javax.media.opengl.GLException;
import javax.media.opengl.glu.GLU;
import com.ardor3d.image.Image;
import com.ardor3d.image.Texture;
import com.ardor3d.image.Texture1D;
import com.ardor3d.image.Texture2D;
import com.ardor3d.image.Texture3D;
import com.ardor3d.image.TextureCubeMap;
import com.ardor3d.image.Texture.ApplyMode;
import com.ardor3d.image.Texture.CombinerFunctionAlpha;
import com.ardor3d.image.Texture.CombinerFunctionRGB;
import com.ardor3d.image.Texture.CombinerOperandAlpha;
import com.ardor3d.image.Texture.CombinerOperandRGB;
import com.ardor3d.image.Texture.CombinerSource;
import com.ardor3d.image.Texture.Type;
import com.ardor3d.image.Texture.WrapAxis;
import com.ardor3d.image.Texture.WrapMode;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.type.ReadOnlyColorRGBA;
import com.ardor3d.renderer.ContextCapabilities;
import com.ardor3d.renderer.ContextManager;
import com.ardor3d.renderer.RenderContext;
import com.ardor3d.renderer.jogl.JoglRenderer;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.RenderState.StateType;
import com.ardor3d.renderer.state.record.RendererRecord;
import com.ardor3d.renderer.state.record.TextureRecord;
import com.ardor3d.renderer.state.record.TextureStateRecord;
import com.ardor3d.renderer.state.record.TextureUnitRecord;
import com.ardor3d.scene.state.jogl.util.JoglRendererUtil;
import com.ardor3d.scene.state.jogl.util.JoglTextureUtil;
import com.ardor3d.util.Constants;
import com.ardor3d.util.TextureKey;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.geom.BufferUtils;
import com.ardor3d.util.stat.StatCollector;
import com.ardor3d.util.stat.StatType;
public class JoglTextureStateUtil {
private static final Logger logger = Logger.getLogger(JoglTextureStateUtil.class.getName());
public final static void load(final Texture texture, final int unit) {
if (texture == null) {
return;
}
final GL gl = GLU.getCurrentGL();
final GLU glu = new GLU();
// our texture type:
final Texture.Type type = texture.getType();
final RenderContext context = ContextManager.getCurrentContext();
final ContextCapabilities caps = context.getCapabilities();
TextureStateRecord record = null;
if (context != null) {
record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
}
// Check we are in the right unit
if (record != null) {
checkAndSetUnit(unit, record, caps);
}
// Create the texture...
if (texture.getTextureKey() != null) {
// First, check if we've already created this texture for our gl context (already on the card)
if (texture.getTextureKey().getContextRep() == null) {
// remove from cache, we'll add it later
TextureManager.removeFromCache(texture.getTextureKey());
} else if (texture.getTextureKey().getContextRep() != context.getGlContextRep()) {
// if texture key has a context already, and it is not ours, complain.
logger.warning("Texture key is morphing contexts: " + texture.getTextureKey());
}
// make sure our context is set.
// XXX don't alter object which is a key in cache hash:
// XXX texture.getTextureKey().setContextRep(context.getGlContextRep());
final TextureKey texKey = new TextureKey(texture.getTextureKey());
texKey.setContextRep(context.getGlContextRep());
// Look for a texture in the cache just like ours, also in the same context.
final Texture cached = TextureManager.findCachedTexture(texKey);
if (cached == null) {
final Texture otherContext = TextureManager.findCachedTexture(texture.getTextureKey());
if (otherContext != null) {
otherContext.createSimpleClone(texture);
}
texture.setTextureKey(texKey);
TextureManager.addToCache(texture);
} else if (cached.getTextureId() != 0) {
texture.setTextureId(cached.getTextureId());
gl.glBindTexture(getGLType(type), cached.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
return;
}
}
final IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
gl.glGenTextures(id.limit(), id);
texture.setTextureId(id.get(0));
gl.glBindTexture(getGLType(type), texture.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
TextureManager.registerForCleanup(texture.getTextureKey(), texture.getTextureId());
// pass image data to OpenGL
final Image image = texture.getImage();
final boolean hasBorder = texture.hasBorder();
if (image == null) {
logger.warning("Image data for texture is null.");
}
// set alignment to support images with width % 4 != 0, as images are
// not aligned
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
// Get texture image data. Not all textures have image data.
// For example, ApplyMode.Combine modes can use primary colors,
// texture output, and constants to modify fragments via the
// texture units.
if (image != null) {
if (!caps.isNonPowerOfTwoTextureSupported()
&& (!MathUtils.isPowerOfTwo(image.getWidth()) || !MathUtils.isPowerOfTwo(image.getHeight()))) {
logger.warning("(card unsupported) Attempted to apply texture with size that is not power of 2: "
+ image.getWidth() + " x " + image.getHeight());
final int maxSize = caps.getMaxTextureSize();
final int actualWidth = image.getWidth();
int w = MathUtils.nearestPowerOfTwo(actualWidth);
if (w > maxSize) {
w = maxSize;
}
final int actualHeight = image.getHeight();
int h = MathUtils.nearestPowerOfTwo(actualHeight);
if (h > maxSize) {
h = maxSize;
}
logger.warning("Rescaling image to " + w + " x " + h + " !!!");
// must rescale image to get "top" mipmap texture image
final int pixFormat = JoglTextureUtil.getGLPixelFormat(texture.getTextureKey().getFormat(), image
.getFormat(), context.getCapabilities());
final int pixDataType = JoglTextureUtil.getGLPixelDataType(image.getFormat());
final int bpp = JoglTextureUtil.bytesPerPixel(pixFormat, pixDataType);
final ByteBuffer scaledImage = BufferUtils.createByteBuffer((w + 4) * h * bpp);
final int error = glu.gluScaleImage(pixFormat, actualWidth, actualHeight, pixDataType,
image.getData(0), w, h, pixDataType, scaledImage);
if (error != 0) {
final int errorCode = gl.glGetError();
if (errorCode != GL.GL_NO_ERROR) {
throw new GLException(glu.gluErrorString(errorCode));
}
}
image.setWidth(w);
image.setHeight(h);
image.setData(scaledImage);
}
if (!texture.getMinificationFilter().usesMipMapLevels()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// Load textures which do not need mipmap auto-generating and
// which aren't using compressed images.
switch (texture.getType()) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), image.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), image.getDepth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), data);
} else {
logger.warning("This card does not support Texture3D.");
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getWidth(), hasBorder ? 1 : 0,
JoglTextureUtil.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face.ordinal()));
}
} else {
logger.warning("This card does not support Cubemaps.");
}
break;
}
} else if (texture.getMinificationFilter().usesMipMapLevels() && !image.hasMipmaps()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// For textures which need mipmaps auto-generating and which
// aren't using compressed images, generate the mipmaps.
// A new mipmap builder may be needed to build mipmaps for
// compressed textures.
if (caps.isAutomaticMipmapsSupported()) {
// Flag the card to generate mipmaps
gl.glTexParameteri(getGLType(type), GL.GL_GENERATE_MIPMAP_SGIS, GL.GL_TRUE);
}
switch (type) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), image
.getData(0));
} else {
// send to card
glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
}
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(0));
} else {
// Note: JOGL's GLU class does not support
// gluBuild1DMipmaps.
logger
.warning("non-fbo 1d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), image.getDepth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
} else {
// Note: JOGL's GLU class does not support
// gluBuild3DMipmaps.
logger
.warning("non-fbo 3d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
} else {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send to card
glu.gluBuild2DMipmaps(getGLCubeMapFace(face), JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
}
} else {
logger.warning("This card does not support Cubemaps.");
return;
}
break;
}
} else {
// Here we handle textures that are either compressed or have
// predefined mipmaps.
// Get mipmap data sizes and amount of mipmaps to send to
// opengl. Then loop through all mipmaps and send them.
int[] mipSizes = image.getMipMapSizes();
ByteBuffer data = image.getData(0);
if (type == Type.ThreeDimensional) {
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
}
int max = 1;
int pos = 0;
if (mipSizes == null) {
mipSizes = new int[] { data.capacity() };
} else if (texture.getMinificationFilter().usesMipMapLevels()) {
max = mipSizes.length;
}
for (int m = 0; m < max; m++) {
final int width = Math.max(1, image.getWidth() >> m);
final int height = type != Type.OneDimensional ? Math.max(1, image.getHeight() >> m) : 0;
final int depth = type == Type.ThreeDimensional ? Math.max(1, image.getDepth() >> m) : 0;
data.position(pos);
data.limit(pos + mipSizes[m]);
switch (type) {
case TwoDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil
- .getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1 : 0, data
- .limit(), data);
+ .getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1 : 0,
+ mipSizes[m], data);
} else {
gl.glTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case OneDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil
- .getGLInternalFormat(image.getFormat()), width, hasBorder ? 1 : 0,
- data.limit(), data);
+ .getGLInternalFormat(image.getFormat()), width, hasBorder ? 1 : 0, mipSizes[m],
+ data);
} else {
gl.glTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
break;
case ThreeDimensional:
// already checked for support above...
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, depth, hasBorder ? 1
- : 0, data.limit(), data);
+ : 0, mipSizes[m], data);
} else {
gl.glTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, depth, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case CubeMap:
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
- : 0, data.limit(), data);
+ : 0, mipSizes[m], data);
} else {
gl.glTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
: 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
}
}
break;
}
pos += mipSizes[m];
}
data.clear();
}
}
}
public static void apply(final JoglRenderer renderer, final TextureState state) {
final GL gl = GLU.getCurrentGL();
// ask for the current state record
final RenderContext context = ContextManager.getCurrentContext();
final ContextCapabilities caps = context.getCapabilities();
final TextureStateRecord record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
context.setCurrentState(StateType.Texture, state);
if (state.isEnabled()) {
Texture texture;
Texture.Type type;
TextureUnitRecord unitRecord;
TextureRecord texRecord;
final int glHint = JoglTextureUtil.getPerspHint(state.getCorrectionType());
if (!record.isValid() || record.hint != glHint) {
// set up correction mode
gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, glHint);
record.hint = glHint;
}
// loop through all available texture units...
for (int i = 0; i < caps.getNumberOfTotalTextureUnits(); i++) {
unitRecord = record.units[i];
// grab a texture for this unit, if available
texture = state.getTexture(i);
// check for invalid textures - ones that have no opengl id and
// no image data
if (texture != null && texture.getTextureId() == 0 && texture.getImage() == null) {
texture = null;
}
// null textures above fixed limit do not need to be disabled
// since they are not really part of the pipeline.
if (texture == null) {
if (i >= caps.getNumberOfFixedTextureUnits()) {
continue;
} else {
// a null texture indicates no texturing at this unit
// Disable texturing on this unit if enabled.
disableTexturing(unitRecord, record, i, caps);
if (i < state._idCache.length) {
state._idCache[i] = 0;
}
// next texture!
continue;
}
}
type = texture.getType();
// disable other texturing types for this unit, if enabled.
disableTexturing(unitRecord, record, i, type, caps);
// Time to bind the texture, so see if we need to load in image
// data for this texture.
if (texture.getTextureId() == 0) {
// texture not yet loaded.
// this will load and bind and set the records...
load(texture, i);
if (texture.getTextureId() == 0) {
continue;
}
} else {
// texture already exists in OpenGL, just bind it if needed
if (!unitRecord.isValid() || unitRecord.boundTexture != texture.getTextureId()) {
checkAndSetUnit(i, record, caps);
gl.glBindTexture(getGLType(type), texture.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
unitRecord.boundTexture = texture.getTextureId();
}
}
// Grab our record for this texture
texRecord = record.getTextureRecord(texture.getTextureId(), texture.getType());
// Set the idCache value for this unit of this texture state
// This is done so during state comparison we don't have to
// spend a lot of time pulling out classes and finding field
// data.
state._idCache[i] = texture.getTextureId();
// Some texture things only apply to fixed function pipeline
if (i < caps.getNumberOfFixedTextureUnits()) {
// Enable 2D texturing on this unit if not enabled.
if (!unitRecord.isValid() || !unitRecord.enabled[type.ordinal()]) {
checkAndSetUnit(i, record, caps);
gl.glEnable(getGLType(type));
unitRecord.enabled[type.ordinal()] = true;
}
// Set our blend color, if needed.
applyBlendColor(texture, unitRecord, i, record, caps);
// Set the texture environment mode if this unit isn't
// already set properly
applyEnvMode(texture.getApply(), unitRecord, i, record, caps);
// If our mode is combine, and we support multitexturing
// apply combine settings.
if (texture.getApply() == ApplyMode.Combine && caps.isMultitextureSupported()
&& caps.isEnvCombineSupported()) {
applyCombineFactors(texture, unitRecord, i, record, caps);
}
}
// Other items only apply to textures below the frag unit limit
if (i < caps.getNumberOfFragmentTextureUnits()) {
// texture specific params
applyFilter(texture, texRecord, i, record, caps);
applyWrap(texture, texRecord, i, record, caps);
applyShadow(texture, texRecord, i, record, caps);
// Set our border color, if needed.
applyBorderColor(texture, texRecord, i, record, caps);
// all states have now been applied for a tex record, so we
// can safely make it valid
if (!texRecord.isValid()) {
texRecord.validate();
}
}
// Other items only apply to textures below the frag tex coord
// unit limit
if (i < caps.getNumberOfFragmentTexCoordUnits()) {
// Now time to play with texture matrices
// Determine which transforms to do.
applyTextureTransforms(texture, i, record, caps);
// Now let's look at automatic texture coordinate
// generation.
applyTexCoordGeneration(texture, unitRecord, i, record, caps);
// Set our texture lod bias, if needed.
applyLodBias(texture, unitRecord, i, record, caps);
}
}
} else {
// turn off texturing
TextureUnitRecord unitRecord;
if (caps.isMultitextureSupported()) {
for (int i = 0; i < caps.getNumberOfFixedTextureUnits(); i++) {
unitRecord = record.units[i];
disableTexturing(unitRecord, record, i, caps);
}
} else {
unitRecord = record.units[0];
disableTexturing(unitRecord, record, 0, caps);
}
}
if (!record.isValid()) {
record.validate();
}
}
private static void disableTexturing(final TextureUnitRecord unitRecord, final TextureStateRecord record,
final int unit, final Type exceptedType, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (exceptedType != Type.TwoDimensional) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.TwoDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_2D);
unitRecord.enabled[Type.TwoDimensional.ordinal()] = false;
}
}
if (exceptedType != Type.OneDimensional) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.OneDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_1D);
unitRecord.enabled[Type.OneDimensional.ordinal()] = false;
}
}
if (caps.isTexture3DSupported() && exceptedType != Type.ThreeDimensional) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.ThreeDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_3D);
unitRecord.enabled[Type.ThreeDimensional.ordinal()] = false;
}
}
if (caps.isTextureCubeMapSupported() && exceptedType != Type.CubeMap) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.CubeMap.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_CUBE_MAP);
unitRecord.enabled[Type.CubeMap.ordinal()] = false;
}
}
}
private static void disableTexturing(final TextureUnitRecord unitRecord, final TextureStateRecord record,
final int unit, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (!unitRecord.isValid() || unitRecord.enabled[Type.TwoDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_2D);
unitRecord.enabled[Type.TwoDimensional.ordinal()] = false;
}
if (!unitRecord.isValid() || unitRecord.enabled[Type.OneDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_1D);
unitRecord.enabled[Type.OneDimensional.ordinal()] = false;
}
if (caps.isTexture3DSupported()) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.ThreeDimensional.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_3D);
unitRecord.enabled[Type.ThreeDimensional.ordinal()] = false;
}
}
if (caps.isTextureCubeMapSupported()) {
if (!unitRecord.isValid() || unitRecord.enabled[Type.CubeMap.ordinal()]) {
// Check we are in the right unit
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_CUBE_MAP);
unitRecord.enabled[Type.CubeMap.ordinal()] = false;
}
}
}
public static void applyCombineFactors(final Texture texture, final TextureUnitRecord unitRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
// check that this is a valid fixed function unit. glTexEnv is only
// supported for unit < GL_MAX_TEXTURE_UNITS
if (unit >= caps.getNumberOfFixedTextureUnits()) {
return;
}
// first thing's first... if we are doing dot3 and don't
// support it, disable this texture.
boolean checked = false;
if (!caps.isEnvDot3TextureCombineSupported()
&& (texture.getCombineFuncRGB() == CombinerFunctionRGB.Dot3RGB || texture.getCombineFuncRGB() == CombinerFunctionRGB.Dot3RGBA)) {
// disable
disableTexturing(unitRecord, record, unit, caps);
// No need to continue
return;
}
// Okay, now let's set our scales if we need to:
// First RGB Combine scale
if (!unitRecord.isValid() || unitRecord.envRGBScale != texture.getCombineScaleRGB()) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, texture.getCombineScaleRGB().floatValue());
unitRecord.envRGBScale = texture.getCombineScaleRGB();
} // Then Alpha Combine scale
if (!unitRecord.isValid() || unitRecord.envAlphaScale != texture.getCombineScaleAlpha()) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_ALPHA_SCALE, texture.getCombineScaleAlpha().floatValue());
unitRecord.envAlphaScale = texture.getCombineScaleAlpha();
}
// Time to set the RGB combines
final CombinerFunctionRGB rgbCombineFunc = texture.getCombineFuncRGB();
if (!unitRecord.isValid() || unitRecord.rgbCombineFunc != rgbCombineFunc) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_COMBINE_RGB, JoglTextureUtil.getGLCombineFuncRGB(rgbCombineFunc));
unitRecord.rgbCombineFunc = rgbCombineFunc;
}
CombinerSource combSrcRGB = texture.getCombineSrc0RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB0 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE0_RGB, JoglTextureUtil.getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB0 = combSrcRGB;
}
CombinerOperandRGB combOpRGB = texture.getCombineOp0RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB0 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND0_RGB, JoglTextureUtil.getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB0 = combOpRGB;
}
// We only need to do Arg1 or Arg2 if we aren't in Replace mode
if (rgbCombineFunc != CombinerFunctionRGB.Replace) {
combSrcRGB = texture.getCombineSrc1RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB1 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE1_RGB, JoglTextureUtil.getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB1 = combSrcRGB;
}
combOpRGB = texture.getCombineOp1RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB1 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND1_RGB, JoglTextureUtil.getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB1 = combOpRGB;
}
// We only need to do Arg2 if we are in Interpolate mode
if (rgbCombineFunc == CombinerFunctionRGB.Interpolate) {
combSrcRGB = texture.getCombineSrc2RGB();
if (!unitRecord.isValid() || unitRecord.combSrcRGB2 != combSrcRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE2_RGB, JoglTextureUtil.getGLCombineSrc(combSrcRGB));
unitRecord.combSrcRGB2 = combSrcRGB;
}
combOpRGB = texture.getCombineOp2RGB();
if (!unitRecord.isValid() || unitRecord.combOpRGB2 != combOpRGB) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND2_RGB, JoglTextureUtil.getGLCombineOpRGB(combOpRGB));
unitRecord.combOpRGB2 = combOpRGB;
}
}
}
// Now Alpha combines
final CombinerFunctionAlpha alphaCombineFunc = texture.getCombineFuncAlpha();
if (!unitRecord.isValid() || unitRecord.alphaCombineFunc != alphaCombineFunc) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_COMBINE_ALPHA, JoglTextureUtil
.getGLCombineFuncAlpha(alphaCombineFunc));
unitRecord.alphaCombineFunc = alphaCombineFunc;
}
CombinerSource combSrcAlpha = texture.getCombineSrc0Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha0 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE0_ALPHA, JoglTextureUtil.getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha0 = combSrcAlpha;
}
CombinerOperandAlpha combOpAlpha = texture.getCombineOp0Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha0 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND0_ALPHA, JoglTextureUtil.getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha0 = combOpAlpha;
}
// We only need to do Arg1 or Arg2 if we aren't in Replace mode
if (alphaCombineFunc != CombinerFunctionAlpha.Replace) {
combSrcAlpha = texture.getCombineSrc1Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha1 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE1_ALPHA, JoglTextureUtil.getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha1 = combSrcAlpha;
}
combOpAlpha = texture.getCombineOp1Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha1 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND1_ALPHA, JoglTextureUtil.getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha1 = combOpAlpha;
}
// We only need to do Arg2 if we are in Interpolate mode
if (alphaCombineFunc == CombinerFunctionAlpha.Interpolate) {
combSrcAlpha = texture.getCombineSrc2Alpha();
if (!unitRecord.isValid() || unitRecord.combSrcAlpha2 != combSrcAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SOURCE2_ALPHA, JoglTextureUtil.getGLCombineSrc(combSrcAlpha));
unitRecord.combSrcAlpha2 = combSrcAlpha;
}
combOpAlpha = texture.getCombineOp2Alpha();
if (!unitRecord.isValid() || unitRecord.combOpAlpha2 != combOpAlpha) {
if (!checked) {
checkAndSetUnit(unit, record, caps);
checked = true;
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_OPERAND2_ALPHA, JoglTextureUtil
.getGLCombineOpAlpha(combOpAlpha));
unitRecord.combOpAlpha2 = combOpAlpha;
}
}
}
}
public static void applyEnvMode(final ApplyMode mode, final TextureUnitRecord unitRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (!unitRecord.isValid() || unitRecord.envMode != mode) {
checkAndSetUnit(unit, record, caps);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, JoglTextureUtil.getGLEnvMode(mode));
unitRecord.envMode = mode;
}
}
public static void applyBlendColor(final Texture texture, final TextureUnitRecord unitRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final ReadOnlyColorRGBA texBlend = texture.getBlendColor();
if (!unitRecord.isValid() || !unitRecord.blendColor.equals(texBlend)) {
checkAndSetUnit(unit, record, caps);
TextureRecord.colorBuffer.clear();
TextureRecord.colorBuffer.put(texBlend.getRed()).put(texBlend.getGreen()).put(texBlend.getBlue()).put(
texBlend.getAlpha());
TextureRecord.colorBuffer.rewind();
gl.glTexEnvfv(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_COLOR, TextureRecord.colorBuffer);
unitRecord.blendColor.set(texBlend);
}
}
public static void applyLodBias(final Texture texture, final TextureUnitRecord unitRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (caps.isTextureLodBiasSupported()) {
final float bias = texture.getLodBias() < caps.getMaxLodBias() ? texture.getLodBias() : caps
.getMaxLodBias();
if (!unitRecord.isValid() || unitRecord.lodBias != bias) {
checkAndSetUnit(unit, record, caps);
gl.glTexEnvf(GL.GL_TEXTURE_FILTER_CONTROL_EXT, GL.GL_TEXTURE_LOD_BIAS_EXT, bias);
unitRecord.lodBias = bias;
}
}
}
public static void applyBorderColor(final Texture texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final ReadOnlyColorRGBA texBorder = texture.getBorderColor();
if (!texRecord.isValid() || !texRecord.borderColor.equals(texBorder)) {
TextureRecord.colorBuffer.clear();
TextureRecord.colorBuffer.put(texBorder.getRed()).put(texBorder.getGreen()).put(texBorder.getBlue()).put(
texBorder.getAlpha());
TextureRecord.colorBuffer.rewind();
gl.glTexParameterfv(getGLType(texture.getType()), GL.GL_TEXTURE_BORDER_COLOR, TextureRecord.colorBuffer);
texRecord.borderColor.set(texBorder);
}
}
public static void applyTextureTransforms(final Texture texture, final int unit, final TextureStateRecord record,
final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final boolean needsReset = !record.units[unit].identityMatrix;
// Should we apply the transform?
final boolean doTrans = !texture.getTextureMatrix().isIdentity();
// Now do them.
final RendererRecord matRecord = ContextManager.getCurrentContext().getRendererRecord();
if (doTrans) {
checkAndSetUnit(unit, record, caps);
JoglRendererUtil.switchMode(matRecord, GL.GL_TEXTURE);
record.tmp_matrixBuffer.rewind();
texture.getTextureMatrix().toDoubleBuffer(record.tmp_matrixBuffer, true);
record.tmp_matrixBuffer.rewind();
gl.glLoadMatrixd(record.tmp_matrixBuffer);
record.units[unit].identityMatrix = false;
} else if (needsReset) {
checkAndSetUnit(unit, record, caps);
JoglRendererUtil.switchMode(matRecord, GL.GL_TEXTURE);
gl.glLoadIdentity();
record.units[unit].identityMatrix = true;
}
// Switch back to the modelview matrix for further operations
JoglRendererUtil.switchMode(matRecord, GL.GL_MODELVIEW);
}
public static void applyTexCoordGeneration(final Texture texture, final TextureUnitRecord unitRecord,
final int unit, final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
switch (texture.getEnvironmentalMapMode()) {
case None:
// No coordinate generation
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenR) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenS) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenT) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = false;
}
break;
case SphereMap:
// generate spherical texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL.GL_SPHERE_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
unitRecord.textureGenSMode = GL.GL_SPHERE_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL.GL_SPHERE_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
unitRecord.textureGenTMode = GL.GL_SPHERE_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || unitRecord.textureGenR) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = false;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
break;
case NormalMap:
// generate spherical texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL.GL_NORMAL_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_NORMAL_MAP);
unitRecord.textureGenSMode = GL.GL_NORMAL_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL.GL_NORMAL_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_NORMAL_MAP);
unitRecord.textureGenTMode = GL.GL_NORMAL_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL.GL_NORMAL_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_NORMAL_MAP);
unitRecord.textureGenTMode = GL.GL_NORMAL_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
break;
case ReflectionMap:
// generate spherical texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL.GL_REFLECTION_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_REFLECTION_MAP);
unitRecord.textureGenSMode = GL.GL_REFLECTION_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL.GL_REFLECTION_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_REFLECTION_MAP);
unitRecord.textureGenTMode = GL.GL_REFLECTION_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL.GL_REFLECTION_MAP) {
checkAndSetUnit(unit, record, caps);
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_REFLECTION_MAP);
unitRecord.textureGenTMode = GL.GL_REFLECTION_MAP;
}
if (!unitRecord.isValid() || unitRecord.textureGenQ) {
checkAndSetUnit(unit, record, caps);
gl.glDisable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = false;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
checkAndSetUnit(unit, record, caps);
gl.glEnable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
break;
case EyeLinear:
// do here because we don't check planes
checkAndSetUnit(unit, record, caps);
// generate eye linear texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenQMode != GL.GL_EYE_LINEAR) {
gl.glTexGeni(GL.GL_Q, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
unitRecord.textureGenQMode = GL.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL.GL_EYE_LINEAR) {
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
unitRecord.textureGenRMode = GL.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL.GL_EYE_LINEAR) {
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
unitRecord.textureGenSMode = GL.GL_EYE_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL.GL_EYE_LINEAR) {
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
unitRecord.textureGenTMode = GL.GL_EYE_LINEAR;
}
record.prepPlane(texture.getEnvPlaneS(), TextureStateRecord.DEFAULT_S_PLANE);
gl.glTexGenfv(GL.GL_S, GL.GL_EYE_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneT(), TextureStateRecord.DEFAULT_T_PLANE);
gl.glTexGenfv(GL.GL_T, GL.GL_EYE_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneR(), TextureStateRecord.DEFAULT_R_PLANE);
gl.glTexGenfv(GL.GL_R, GL.GL_EYE_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneQ(), TextureStateRecord.DEFAULT_Q_PLANE);
gl.glTexGenfv(GL.GL_Q, GL.GL_EYE_PLANE, record.plane);
if (!unitRecord.isValid() || !unitRecord.textureGenQ) {
gl.glEnable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
gl.glEnable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
gl.glEnable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
gl.glEnable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
break;
case ObjectLinear:
// do here because we don't check planes
checkAndSetUnit(unit, record, caps);
// generate object linear texture coordinates
if (!unitRecord.isValid() || unitRecord.textureGenQMode != GL.GL_OBJECT_LINEAR) {
gl.glTexGeni(GL.GL_Q, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
unitRecord.textureGenSMode = GL.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenRMode != GL.GL_OBJECT_LINEAR) {
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
unitRecord.textureGenTMode = GL.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenSMode != GL.GL_OBJECT_LINEAR) {
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
unitRecord.textureGenSMode = GL.GL_OBJECT_LINEAR;
}
if (!unitRecord.isValid() || unitRecord.textureGenTMode != GL.GL_OBJECT_LINEAR) {
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
unitRecord.textureGenTMode = GL.GL_OBJECT_LINEAR;
}
record.prepPlane(texture.getEnvPlaneS(), TextureStateRecord.DEFAULT_S_PLANE);
gl.glTexGenfv(GL.GL_S, GL.GL_OBJECT_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneT(), TextureStateRecord.DEFAULT_T_PLANE);
gl.glTexGenfv(GL.GL_T, GL.GL_OBJECT_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneR(), TextureStateRecord.DEFAULT_R_PLANE);
gl.glTexGenfv(GL.GL_R, GL.GL_OBJECT_PLANE, record.plane);
record.prepPlane(texture.getEnvPlaneQ(), TextureStateRecord.DEFAULT_Q_PLANE);
gl.glTexGenfv(GL.GL_Q, GL.GL_OBJECT_PLANE, record.plane);
if (!unitRecord.isValid() || !unitRecord.textureGenQ) {
gl.glEnable(GL.GL_TEXTURE_GEN_Q);
unitRecord.textureGenQ = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenR) {
gl.glEnable(GL.GL_TEXTURE_GEN_R);
unitRecord.textureGenR = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenS) {
gl.glEnable(GL.GL_TEXTURE_GEN_S);
unitRecord.textureGenS = true;
}
if (!unitRecord.isValid() || !unitRecord.textureGenT) {
gl.glEnable(GL.GL_TEXTURE_GEN_T);
unitRecord.textureGenT = true;
}
break;
}
}
// If we support multtexturing, specify the unit we are affecting.
public static void checkAndSetUnit(final int unit, final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
// No need to worry about valid record, since invalidate sets record's
// currentUnit to -1.
if (record.currentUnit != unit) {
if (unit >= caps.getNumberOfTotalTextureUnits() || !caps.isMultitextureSupported() || unit < 0) {
// ignore this request as it is not valid for the user's hardware.
return;
}
gl.glActiveTexture(GL.GL_TEXTURE0 + unit);
record.currentUnit = unit;
}
}
/**
* Check if the filter settings of this particular texture have been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the texture in gl
* @param record
*/
public static void applyShadow(final Texture texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final Type type = texture.getType();
if (caps.isDepthTextureSupported()) {
final int depthMode = JoglTextureUtil.getGLDepthTextureMode(texture.getDepthMode());
// set up magnification filter
if (!texRecord.isValid() || texRecord.depthTextureMode != depthMode) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(getGLType(type), GL.GL_DEPTH_TEXTURE_MODE_ARB, depthMode);
texRecord.depthTextureMode = depthMode;
}
}
if (caps.isARBShadowSupported()) {
final int depthCompareMode = JoglTextureUtil.getGLDepthTextureCompareMode(texture.getDepthCompareMode());
// set up magnification filter
if (!texRecord.isValid() || texRecord.depthTextureCompareMode != depthCompareMode) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(getGLType(type), GL.GL_TEXTURE_COMPARE_MODE_ARB, depthCompareMode);
texRecord.depthTextureCompareMode = depthCompareMode;
}
final int depthCompareFunc = JoglTextureUtil.getGLDepthTextureCompareFunc(texture.getDepthCompareFunc());
// set up magnification filter
if (!texRecord.isValid() || texRecord.depthTextureCompareFunc != depthCompareFunc) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(getGLType(type), GL.GL_TEXTURE_COMPARE_FUNC_ARB, depthCompareFunc);
texRecord.depthTextureCompareFunc = depthCompareFunc;
}
}
}
/**
* Check if the filter settings of this particular texture have been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the texture in gl
* @param record
*/
public static void applyFilter(final Texture texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final Type type = texture.getType();
final int magFilter = JoglTextureUtil.getGLMagFilter(texture.getMagnificationFilter());
// set up magnification filter
if (!texRecord.isValid() || texRecord.magFilter != magFilter) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(getGLType(type), GL.GL_TEXTURE_MAG_FILTER, magFilter);
texRecord.magFilter = magFilter;
}
final int minFilter = JoglTextureUtil.getGLMinFilter(texture.getMinificationFilter());
// set up mipmap filter
if (!texRecord.isValid() || texRecord.minFilter != minFilter) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(getGLType(type), GL.GL_TEXTURE_MIN_FILTER, minFilter);
texRecord.minFilter = minFilter;
}
// set up aniso filter
if (caps.isAnisoSupported()) {
float aniso = texture.getAnisotropicFilterPercent() * (caps.getMaxAnisotropic() - 1.0f);
aniso += 1.0f;
if (!texRecord.isValid() || texRecord.anisoLevel != aniso) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameterf(getGLType(type), GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso);
texRecord.anisoLevel = aniso;
}
}
}
/**
* Check if the wrap mode of this particular texture has been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
public static void applyWrap(final Texture3D texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (!caps.isTexture3DSupported()) {
return;
}
final int wrapS = getGLWrap(texture.getWrap(WrapAxis.S), caps);
final int wrapT = getGLWrap(texture.getWrap(WrapAxis.T), caps);
final int wrapR = getGLWrap(texture.getWrap(WrapAxis.R), caps);
if (!texRecord.isValid() || texRecord.wrapS != wrapS) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, wrapS);
texRecord.wrapS = wrapS;
}
if (!texRecord.isValid() || texRecord.wrapT != wrapT) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, wrapT);
texRecord.wrapT = wrapT;
}
if (!texRecord.isValid() || texRecord.wrapR != wrapR) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_R, wrapR);
texRecord.wrapR = wrapR;
}
}
/**
* Check if the wrap mode of this particular texture has been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
public static void applyWrap(final Texture1D texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final int wrapS = getGLWrap(texture.getWrap(WrapAxis.S), caps);
if (!texRecord.isValid() || texRecord.wrapS != wrapS) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_WRAP_S, wrapS);
texRecord.wrapS = wrapS;
}
}
/**
* Check if the wrap mode of this particular texture has been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
public static void applyWrap(final Texture texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
if (texture instanceof Texture2D) {
applyWrap((Texture2D) texture, texRecord, unit, record, caps);
} else if (texture instanceof Texture1D) {
applyWrap((Texture1D) texture, texRecord, unit, record, caps);
} else if (texture instanceof Texture3D) {
applyWrap((Texture3D) texture, texRecord, unit, record, caps);
} else if (texture instanceof TextureCubeMap) {
applyWrap((TextureCubeMap) texture, texRecord, unit, record, caps);
}
}
/**
* Check if the wrap mode of this particular texture has been changed and apply as needed.
*
* @param texture
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
public static void applyWrap(final Texture2D texture, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
final int wrapS = getGLWrap(texture.getWrap(WrapAxis.S), caps);
final int wrapT = getGLWrap(texture.getWrap(WrapAxis.T), caps);
if (!texRecord.isValid() || texRecord.wrapS != wrapS) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapS);
texRecord.wrapS = wrapS;
}
if (!texRecord.isValid() || texRecord.wrapT != wrapT) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapT);
texRecord.wrapT = wrapT;
}
}
/**
* Check if the wrap mode of this particular texture has been changed and apply as needed.
*
* @param cubeMap
* our texture object
* @param texRecord
* our record of the last state of the unit in gl
* @param record
*/
public static void applyWrap(final TextureCubeMap cubeMap, final TextureRecord texRecord, final int unit,
final TextureStateRecord record, final ContextCapabilities caps) {
final GL gl = GLU.getCurrentGL();
if (!caps.isTexture3DSupported()) {
return;
}
final int wrapS = getGLWrap(cubeMap.getWrap(WrapAxis.S), caps);
final int wrapT = getGLWrap(cubeMap.getWrap(WrapAxis.T), caps);
final int wrapR = getGLWrap(cubeMap.getWrap(WrapAxis.R), caps);
if (!texRecord.isValid() || texRecord.wrapS != wrapS) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_CUBE_MAP, GL.GL_TEXTURE_WRAP_S, wrapS);
texRecord.wrapS = wrapS;
}
if (!texRecord.isValid() || texRecord.wrapT != wrapT) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_CUBE_MAP, GL.GL_TEXTURE_WRAP_T, wrapT);
texRecord.wrapT = wrapT;
}
if (!texRecord.isValid() || texRecord.wrapR != wrapR) {
checkAndSetUnit(unit, record, caps);
gl.glTexParameteri(GL.GL_TEXTURE_CUBE_MAP, GL.GL_TEXTURE_WRAP_R, wrapR);
texRecord.wrapR = wrapR;
}
}
/*
* (non-Javadoc)
*
* @see com.ardor3d.scene.state.TextureState#delete(int)
*/
public static void delete(final int unit, final Texture tex) {
final GL gl = GLU.getCurrentGL();
// ask for the current state record
final RenderContext context = ContextManager.getCurrentContext();
final TextureStateRecord record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
final int texId = tex.getTextureId();
final IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
id.put(texId);
id.rewind();
tex.setTextureId(0);
gl.glDeleteTextures(id.limit(), id);
// if the texture was currently bound glDeleteTextures reverts the
// binding to 0
// however we still have to clear it from currentTexture.
record.removeTextureRecord(texId);
}
public static void deleteTextureId(final int textureId) {
final GL gl = GLU.getCurrentGL();
// ask for the current state record
final RenderContext context = ContextManager.getCurrentContext();
final TextureStateRecord record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
final IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
id.put(textureId);
id.rewind();
gl.glDeleteTextures(id.limit(), id);
record.removeTextureRecord(textureId);
}
/**
* Useful for external jogl based classes that need to safely set the current texture.
*/
public static void doTextureBind(final int textureId, final int unit, final Type type) {
final GL gl = GLU.getCurrentGL();
// ask for the current state record
final RenderContext context = ContextManager.getCurrentContext();
final ContextCapabilities caps = context.getCapabilities();
final TextureStateRecord record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
// Set this to null because no current state really matches anymore
context.setCurrentState(StateType.Texture, null);
checkAndSetUnit(unit, record, caps);
gl.glBindTexture(getGLType(type), textureId);
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = textureId;
}
}
private static int getGLType(final Type type) {
switch (type) {
case TwoDimensional:
return GL.GL_TEXTURE_2D;
case OneDimensional:
return GL.GL_TEXTURE_1D;
case ThreeDimensional:
return GL.GL_TEXTURE_3D;
case CubeMap:
return GL.GL_TEXTURE_CUBE_MAP;
}
throw new IllegalArgumentException("invalid texture type: " + type);
}
private static int getGLCubeMapFace(final TextureCubeMap.Face face) {
switch (face) {
case PositiveX:
return GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X;
case NegativeX:
return GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
case PositiveY:
return GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
case NegativeY:
return GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
case PositiveZ:
return GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
case NegativeZ:
return GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
}
throw new IllegalArgumentException("invalid cubemap face: " + face);
}
private static int getGLWrap(final WrapMode wrap, final ContextCapabilities caps) {
switch (wrap) {
case Repeat:
return GL.GL_REPEAT;
case MirroredRepeat:
if (caps.isTextureMirroredRepeatSupported()) {
return GL.GL_MIRRORED_REPEAT_ARB;
} else {
return GL.GL_REPEAT;
}
case MirrorClamp:
if (caps.isTextureMirrorClampSupported()) {
return GL.GL_MIRROR_CLAMP_EXT;
}
// FALLS THROUGH
case Clamp:
return GL.GL_CLAMP;
case MirrorBorderClamp:
if (caps.isTextureMirrorBorderClampSupported()) {
return GL.GL_MIRROR_CLAMP_TO_BORDER_EXT;
}
// FALLS THROUGH
case BorderClamp:
if (caps.isTextureBorderClampSupported()) {
return GL.GL_CLAMP_TO_BORDER;
} else {
return GL.GL_CLAMP;
}
case MirrorEdgeClamp:
if (caps.isTextureMirrorEdgeClampSupported()) {
return GL.GL_MIRROR_CLAMP_TO_EDGE_EXT;
}
// FALLS THROUGH
case EdgeClamp:
if (caps.isTextureEdgeClampSupported()) {
return GL.GL_CLAMP_TO_EDGE;
} else {
return GL.GL_CLAMP;
}
}
throw new IllegalArgumentException("invalid WrapMode type: " + wrap);
}
}
| false | true | public final static void load(final Texture texture, final int unit) {
if (texture == null) {
return;
}
final GL gl = GLU.getCurrentGL();
final GLU glu = new GLU();
// our texture type:
final Texture.Type type = texture.getType();
final RenderContext context = ContextManager.getCurrentContext();
final ContextCapabilities caps = context.getCapabilities();
TextureStateRecord record = null;
if (context != null) {
record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
}
// Check we are in the right unit
if (record != null) {
checkAndSetUnit(unit, record, caps);
}
// Create the texture...
if (texture.getTextureKey() != null) {
// First, check if we've already created this texture for our gl context (already on the card)
if (texture.getTextureKey().getContextRep() == null) {
// remove from cache, we'll add it later
TextureManager.removeFromCache(texture.getTextureKey());
} else if (texture.getTextureKey().getContextRep() != context.getGlContextRep()) {
// if texture key has a context already, and it is not ours, complain.
logger.warning("Texture key is morphing contexts: " + texture.getTextureKey());
}
// make sure our context is set.
// XXX don't alter object which is a key in cache hash:
// XXX texture.getTextureKey().setContextRep(context.getGlContextRep());
final TextureKey texKey = new TextureKey(texture.getTextureKey());
texKey.setContextRep(context.getGlContextRep());
// Look for a texture in the cache just like ours, also in the same context.
final Texture cached = TextureManager.findCachedTexture(texKey);
if (cached == null) {
final Texture otherContext = TextureManager.findCachedTexture(texture.getTextureKey());
if (otherContext != null) {
otherContext.createSimpleClone(texture);
}
texture.setTextureKey(texKey);
TextureManager.addToCache(texture);
} else if (cached.getTextureId() != 0) {
texture.setTextureId(cached.getTextureId());
gl.glBindTexture(getGLType(type), cached.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
return;
}
}
final IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
gl.glGenTextures(id.limit(), id);
texture.setTextureId(id.get(0));
gl.glBindTexture(getGLType(type), texture.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
TextureManager.registerForCleanup(texture.getTextureKey(), texture.getTextureId());
// pass image data to OpenGL
final Image image = texture.getImage();
final boolean hasBorder = texture.hasBorder();
if (image == null) {
logger.warning("Image data for texture is null.");
}
// set alignment to support images with width % 4 != 0, as images are
// not aligned
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
// Get texture image data. Not all textures have image data.
// For example, ApplyMode.Combine modes can use primary colors,
// texture output, and constants to modify fragments via the
// texture units.
if (image != null) {
if (!caps.isNonPowerOfTwoTextureSupported()
&& (!MathUtils.isPowerOfTwo(image.getWidth()) || !MathUtils.isPowerOfTwo(image.getHeight()))) {
logger.warning("(card unsupported) Attempted to apply texture with size that is not power of 2: "
+ image.getWidth() + " x " + image.getHeight());
final int maxSize = caps.getMaxTextureSize();
final int actualWidth = image.getWidth();
int w = MathUtils.nearestPowerOfTwo(actualWidth);
if (w > maxSize) {
w = maxSize;
}
final int actualHeight = image.getHeight();
int h = MathUtils.nearestPowerOfTwo(actualHeight);
if (h > maxSize) {
h = maxSize;
}
logger.warning("Rescaling image to " + w + " x " + h + " !!!");
// must rescale image to get "top" mipmap texture image
final int pixFormat = JoglTextureUtil.getGLPixelFormat(texture.getTextureKey().getFormat(), image
.getFormat(), context.getCapabilities());
final int pixDataType = JoglTextureUtil.getGLPixelDataType(image.getFormat());
final int bpp = JoglTextureUtil.bytesPerPixel(pixFormat, pixDataType);
final ByteBuffer scaledImage = BufferUtils.createByteBuffer((w + 4) * h * bpp);
final int error = glu.gluScaleImage(pixFormat, actualWidth, actualHeight, pixDataType,
image.getData(0), w, h, pixDataType, scaledImage);
if (error != 0) {
final int errorCode = gl.glGetError();
if (errorCode != GL.GL_NO_ERROR) {
throw new GLException(glu.gluErrorString(errorCode));
}
}
image.setWidth(w);
image.setHeight(h);
image.setData(scaledImage);
}
if (!texture.getMinificationFilter().usesMipMapLevels()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// Load textures which do not need mipmap auto-generating and
// which aren't using compressed images.
switch (texture.getType()) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), image.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), image.getDepth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), data);
} else {
logger.warning("This card does not support Texture3D.");
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getWidth(), hasBorder ? 1 : 0,
JoglTextureUtil.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face.ordinal()));
}
} else {
logger.warning("This card does not support Cubemaps.");
}
break;
}
} else if (texture.getMinificationFilter().usesMipMapLevels() && !image.hasMipmaps()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// For textures which need mipmaps auto-generating and which
// aren't using compressed images, generate the mipmaps.
// A new mipmap builder may be needed to build mipmaps for
// compressed textures.
if (caps.isAutomaticMipmapsSupported()) {
// Flag the card to generate mipmaps
gl.glTexParameteri(getGLType(type), GL.GL_GENERATE_MIPMAP_SGIS, GL.GL_TRUE);
}
switch (type) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), image
.getData(0));
} else {
// send to card
glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
}
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(0));
} else {
// Note: JOGL's GLU class does not support
// gluBuild1DMipmaps.
logger
.warning("non-fbo 1d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), image.getDepth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
} else {
// Note: JOGL's GLU class does not support
// gluBuild3DMipmaps.
logger
.warning("non-fbo 3d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
} else {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send to card
glu.gluBuild2DMipmaps(getGLCubeMapFace(face), JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
}
} else {
logger.warning("This card does not support Cubemaps.");
return;
}
break;
}
} else {
// Here we handle textures that are either compressed or have
// predefined mipmaps.
// Get mipmap data sizes and amount of mipmaps to send to
// opengl. Then loop through all mipmaps and send them.
int[] mipSizes = image.getMipMapSizes();
ByteBuffer data = image.getData(0);
if (type == Type.ThreeDimensional) {
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
}
int max = 1;
int pos = 0;
if (mipSizes == null) {
mipSizes = new int[] { data.capacity() };
} else if (texture.getMinificationFilter().usesMipMapLevels()) {
max = mipSizes.length;
}
for (int m = 0; m < max; m++) {
final int width = Math.max(1, image.getWidth() >> m);
final int height = type != Type.OneDimensional ? Math.max(1, image.getHeight() >> m) : 0;
final int depth = type == Type.ThreeDimensional ? Math.max(1, image.getDepth() >> m) : 0;
data.position(pos);
data.limit(pos + mipSizes[m]);
switch (type) {
case TwoDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1 : 0, data
.limit(), data);
} else {
gl.glTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case OneDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, hasBorder ? 1 : 0,
data.limit(), data);
} else {
gl.glTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
break;
case ThreeDimensional:
// already checked for support above...
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, depth, hasBorder ? 1
: 0, data.limit(), data);
} else {
gl.glTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, depth, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case CubeMap:
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
: 0, data.limit(), data);
} else {
gl.glTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
: 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
}
}
break;
}
pos += mipSizes[m];
}
data.clear();
}
}
}
| public final static void load(final Texture texture, final int unit) {
if (texture == null) {
return;
}
final GL gl = GLU.getCurrentGL();
final GLU glu = new GLU();
// our texture type:
final Texture.Type type = texture.getType();
final RenderContext context = ContextManager.getCurrentContext();
final ContextCapabilities caps = context.getCapabilities();
TextureStateRecord record = null;
if (context != null) {
record = (TextureStateRecord) context.getStateRecord(StateType.Texture);
}
// Check we are in the right unit
if (record != null) {
checkAndSetUnit(unit, record, caps);
}
// Create the texture...
if (texture.getTextureKey() != null) {
// First, check if we've already created this texture for our gl context (already on the card)
if (texture.getTextureKey().getContextRep() == null) {
// remove from cache, we'll add it later
TextureManager.removeFromCache(texture.getTextureKey());
} else if (texture.getTextureKey().getContextRep() != context.getGlContextRep()) {
// if texture key has a context already, and it is not ours, complain.
logger.warning("Texture key is morphing contexts: " + texture.getTextureKey());
}
// make sure our context is set.
// XXX don't alter object which is a key in cache hash:
// XXX texture.getTextureKey().setContextRep(context.getGlContextRep());
final TextureKey texKey = new TextureKey(texture.getTextureKey());
texKey.setContextRep(context.getGlContextRep());
// Look for a texture in the cache just like ours, also in the same context.
final Texture cached = TextureManager.findCachedTexture(texKey);
if (cached == null) {
final Texture otherContext = TextureManager.findCachedTexture(texture.getTextureKey());
if (otherContext != null) {
otherContext.createSimpleClone(texture);
}
texture.setTextureKey(texKey);
TextureManager.addToCache(texture);
} else if (cached.getTextureId() != 0) {
texture.setTextureId(cached.getTextureId());
gl.glBindTexture(getGLType(type), cached.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
return;
}
}
final IntBuffer id = BufferUtils.createIntBuffer(1);
id.clear();
gl.glGenTextures(id.limit(), id);
texture.setTextureId(id.get(0));
gl.glBindTexture(getGLType(type), texture.getTextureId());
if (Constants.stats) {
StatCollector.addStat(StatType.STAT_TEXTURE_BINDS, 1);
}
if (record != null) {
record.units[unit].boundTexture = texture.getTextureId();
}
TextureManager.registerForCleanup(texture.getTextureKey(), texture.getTextureId());
// pass image data to OpenGL
final Image image = texture.getImage();
final boolean hasBorder = texture.hasBorder();
if (image == null) {
logger.warning("Image data for texture is null.");
}
// set alignment to support images with width % 4 != 0, as images are
// not aligned
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
// Get texture image data. Not all textures have image data.
// For example, ApplyMode.Combine modes can use primary colors,
// texture output, and constants to modify fragments via the
// texture units.
if (image != null) {
if (!caps.isNonPowerOfTwoTextureSupported()
&& (!MathUtils.isPowerOfTwo(image.getWidth()) || !MathUtils.isPowerOfTwo(image.getHeight()))) {
logger.warning("(card unsupported) Attempted to apply texture with size that is not power of 2: "
+ image.getWidth() + " x " + image.getHeight());
final int maxSize = caps.getMaxTextureSize();
final int actualWidth = image.getWidth();
int w = MathUtils.nearestPowerOfTwo(actualWidth);
if (w > maxSize) {
w = maxSize;
}
final int actualHeight = image.getHeight();
int h = MathUtils.nearestPowerOfTwo(actualHeight);
if (h > maxSize) {
h = maxSize;
}
logger.warning("Rescaling image to " + w + " x " + h + " !!!");
// must rescale image to get "top" mipmap texture image
final int pixFormat = JoglTextureUtil.getGLPixelFormat(texture.getTextureKey().getFormat(), image
.getFormat(), context.getCapabilities());
final int pixDataType = JoglTextureUtil.getGLPixelDataType(image.getFormat());
final int bpp = JoglTextureUtil.bytesPerPixel(pixFormat, pixDataType);
final ByteBuffer scaledImage = BufferUtils.createByteBuffer((w + 4) * h * bpp);
final int error = glu.gluScaleImage(pixFormat, actualWidth, actualHeight, pixDataType,
image.getData(0), w, h, pixDataType, scaledImage);
if (error != 0) {
final int errorCode = gl.glGetError();
if (errorCode != GL.GL_NO_ERROR) {
throw new GLException(glu.gluErrorString(errorCode));
}
}
image.setWidth(w);
image.setHeight(h);
image.setData(scaledImage);
}
if (!texture.getMinificationFilter().usesMipMapLevels()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// Load textures which do not need mipmap auto-generating and
// which aren't using compressed images.
switch (texture.getType()) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), image.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0, JoglTextureUtil.getGLInternalFormat(image.getFormat()),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), image.getDepth(), hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), data);
} else {
logger.warning("This card does not support Texture3D.");
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getWidth(), hasBorder ? 1 : 0,
JoglTextureUtil.getGLPixelFormat(image.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face.ordinal()));
}
} else {
logger.warning("This card does not support Cubemaps.");
}
break;
}
} else if (texture.getMinificationFilter().usesMipMapLevels() && !image.hasMipmaps()
&& !JoglTextureUtil.isCompressedType(image.getFormat())) {
// For textures which need mipmaps auto-generating and which
// aren't using compressed images, generate the mipmaps.
// A new mipmap builder may be needed to build mipmaps for
// compressed textures.
if (caps.isAutomaticMipmapsSupported()) {
// Flag the card to generate mipmaps
gl.glTexParameteri(getGLType(type), GL.GL_GENERATE_MIPMAP_SGIS, GL.GL_TRUE);
}
switch (type) {
case TwoDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(), image
.getHeight(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), image
.getData(0));
} else {
// send to card
glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), image.getData(0));
}
break;
case OneDimensional:
// ensure the buffer is ready for reading
image.getData(0).rewind();
if (caps.isAutomaticMipmapsSupported()) {
// send top level to card
gl.glTexImage1D(GL.GL_TEXTURE_1D, 0,
JoglTextureUtil.getGLInternalFormat(image.getFormat()), image.getWidth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(0));
} else {
// Note: JOGL's GLU class does not support
// gluBuild1DMipmaps.
logger
.warning("non-fbo 1d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
break;
case ThreeDimensional:
if (caps.isTexture3DSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
ByteBuffer data = null;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
// send top level to card
gl.glTexImage3D(GL.GL_TEXTURE_3D, 0, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), image.getWidth(), image.getHeight(), image.getDepth(),
hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
} else {
// Note: JOGL's GLU class does not support
// gluBuild3DMipmaps.
logger
.warning("non-fbo 3d mipmap generation is not currently supported. Use DDS or a non-mipmap minification filter.");
return;
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
break;
case CubeMap:
// NOTE: Cubemaps MUST be square, so height is ignored
// on purpose.
if (caps.isTextureCubeMapSupported()) {
if (caps.isAutomaticMipmapsSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send top level to card
gl.glTexImage2D(getGLCubeMapFace(face), 0, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil
.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
} else {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
// ensure the buffer is ready for reading
image.getData(face.ordinal()).rewind();
// send to card
glu.gluBuild2DMipmaps(getGLCubeMapFace(face), JoglTextureUtil
.getGLInternalFormat(image.getFormat()), image.getWidth(),
image.getWidth(), JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), image.getData(face
.ordinal()));
}
}
} else {
logger.warning("This card does not support Cubemaps.");
return;
}
break;
}
} else {
// Here we handle textures that are either compressed or have
// predefined mipmaps.
// Get mipmap data sizes and amount of mipmaps to send to
// opengl. Then loop through all mipmaps and send them.
int[] mipSizes = image.getMipMapSizes();
ByteBuffer data = image.getData(0);
if (type == Type.ThreeDimensional) {
if (caps.isTexture3DSupported()) {
// concat data into single buffer:
int dSize = 0;
int count = 0;
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data = image.getData(x);
dSize += data.limit();
count++;
}
}
// reuse buffer if we can.
if (count != 1) {
data = BufferUtils.createByteBuffer(dSize);
for (int x = 0; x < image.getData().size(); x++) {
if (image.getData(x) != null) {
data.put(image.getData(x));
}
}
// ensure the buffer is ready for reading
data.flip();
}
} else {
logger.warning("This card does not support Texture3D.");
return;
}
}
int max = 1;
int pos = 0;
if (mipSizes == null) {
mipSizes = new int[] { data.capacity() };
} else if (texture.getMinificationFilter().usesMipMapLevels()) {
max = mipSizes.length;
}
for (int m = 0; m < max; m++) {
final int width = Math.max(1, image.getWidth() >> m);
final int height = type != Type.OneDimensional ? Math.max(1, image.getHeight() >> m) : 0;
final int depth = type == Type.ThreeDimensional ? Math.max(1, image.getDepth() >> m) : 0;
data.position(pos);
data.limit(pos + mipSizes[m]);
switch (type) {
case TwoDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1 : 0,
mipSizes[m], data);
} else {
gl.glTexImage2D(GL.GL_TEXTURE_2D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case OneDimensional:
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, hasBorder ? 1 : 0, mipSizes[m],
data);
} else {
gl.glTexImage1D(GL.GL_TEXTURE_1D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, hasBorder ? 1 : 0, JoglTextureUtil.getGLPixelFormat(image
.getFormat()), JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
break;
case ThreeDimensional:
// already checked for support above...
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, depth, hasBorder ? 1
: 0, mipSizes[m], data);
} else {
gl.glTexImage3D(GL.GL_TEXTURE_3D, m, JoglTextureUtil.getGLInternalFormat(image
.getFormat()), width, height, depth, hasBorder ? 1 : 0, JoglTextureUtil
.getGLPixelFormat(image.getFormat()), JoglTextureUtil.getGLPixelDataType(image
.getFormat()), data);
}
break;
case CubeMap:
if (caps.isTextureCubeMapSupported()) {
for (final TextureCubeMap.Face face : TextureCubeMap.Face.values()) {
if (JoglTextureUtil.isCompressedType(image.getFormat())) {
gl.glCompressedTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
: 0, mipSizes[m], data);
} else {
gl.glTexImage2D(getGLCubeMapFace(face), m, JoglTextureUtil
.getGLInternalFormat(image.getFormat()), width, height, hasBorder ? 1
: 0, JoglTextureUtil.getGLPixelFormat(image.getFormat()),
JoglTextureUtil.getGLPixelDataType(image.getFormat()), data);
}
}
}
break;
}
pos += mipSizes[m];
}
data.clear();
}
}
}
|
diff --git a/src/com/android/browser/PhoneUi.java b/src/com/android/browser/PhoneUi.java
index 009989bc..f5a76b92 100644
--- a/src/com/android/browser/PhoneUi.java
+++ b/src/com/android/browser/PhoneUi.java
@@ -1,478 +1,488 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.Log;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.android.browser.UrlInputView.StateListener;
/**
* Ui for regular phone screen sizes
*/
public class PhoneUi extends BaseUi {
private static final String LOGTAG = "PhoneUi";
private PieControlPhone mPieControl;
private NavScreen mNavScreen;
private NavigationBarPhone mNavigationBar;
boolean mExtendedMenuOpen;
boolean mOptionsMenuOpen;
boolean mAnimating;
/**
* @param browser
* @param controller
*/
public PhoneUi(Activity browser, UiController controller) {
super(browser, controller);
mActivity.getActionBar().hide();
setUseQuickControls(BrowserSettings.getInstance().useQuickControls());
mNavigationBar = (NavigationBarPhone) mTitleBar.getNavigationBar();
}
@Override
public void onDestroy() {
hideTitleBar();
}
@Override
public void editUrl(boolean clearInput) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
super.editUrl(clearInput);
}
@Override
public boolean onBackKey() {
if (mNavScreen != null) {
mNavScreen.close();
return true;
}
return super.onBackKey();
}
@Override
public boolean dispatchKey(int code, KeyEvent event) {
return false;
}
@Override
public void onProgressChanged(Tab tab) {
if (tab.inForeground()) {
int progress = tab.getLoadProgress();
mTitleBar.setProgress(progress);
if (progress == 100) {
if (!mOptionsMenuOpen || !mExtendedMenuOpen) {
suggestHideTitleBar();
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
}
} else {
if (!mOptionsMenuOpen || mExtendedMenuOpen) {
if (mUseQuickControls && !mTitleBar.isEditingUrl()) {
mTitleBar.setShowProgressOnly(true);
setTitleGravity(Gravity.TOP);
}
showTitleBar();
}
}
}
}
@Override
public void setActiveTab(final Tab tab) {
mTitleBar.cancelTitleBarAnimation(true);
mTitleBar.setSkipTitleBarAnimations(true);
super.setActiveTab(tab);
BrowserWebView view = (BrowserWebView) tab.getWebView();
// TabControl.setCurrentTab has been called before this,
// so the tab is guaranteed to have a webview
if (view == null) {
Log.e(LOGTAG, "active tab with no webview detected");
return;
}
// Request focus on the top window.
if (mUseQuickControls) {
mPieControl.forceToTop(mContentView);
} else {
// check if title bar is already attached by animation
if (mTitleBar.getParent() == null) {
view.setEmbeddedTitleBar(mTitleBar);
}
}
if (tab.isInVoiceSearchMode()) {
showVoiceTitleBar(tab.getVoiceDisplayTitle(), tab.getVoiceSearchResults());
} else {
revertVoiceTitleBar(tab);
}
// update nav bar state
mNavigationBar.onStateChanged(StateListener.STATE_NORMAL);
updateLockIconToLatest(tab);
tab.getTopWindow().requestFocus();
mTitleBar.setSkipTitleBarAnimations(false);
}
// menu handling callbacks
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
updateMenuState(mActiveTab, menu);
return true;
}
@Override
public void updateMenuState(Tab tab, Menu menu) {
menu.setGroupVisible(R.id.NAV_MENU, (mNavScreen == null));
MenuItem bm = menu.findItem(R.id.bookmarks_menu_id);
if (bm != null) {
bm.setVisible(mNavScreen == null);
}
MenuItem nt = menu.findItem(R.id.new_tab_menu_id);
if (nt != null) {
nt.setVisible(mNavScreen == null);
}
MenuItem abm = menu.findItem(R.id.add_bookmark_menu_id);
if (abm != null) {
abm.setVisible((tab != null) && !tab.isSnapshot());
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mNavScreen != null) {
hideNavScreen(false);
}
return false;
}
@Override
public void onContextMenuCreated(Menu menu) {
hideTitleBar();
}
@Override
public void onContextMenuClosed(Menu menu, boolean inLoad) {
if (inLoad) {
showTitleBar();
}
}
// action mode callbacks
@Override
public void onActionModeStarted(ActionMode mode) {
if (!isEditingUrl()) {
hideTitleBar();
}
}
@Override
public void onActionModeFinished(boolean inLoad) {
if (inLoad) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(true);
}
showTitleBar();
}
mActivity.getActionBar().hide();
}
@Override
protected void setTitleGravity(int gravity) {
if (mUseQuickControls) {
FrameLayout.LayoutParams lp =
(FrameLayout.LayoutParams) mTitleBar.getLayoutParams();
lp.gravity = gravity;
mTitleBar.setLayoutParams(lp);
} else {
super.setTitleGravity(gravity);
}
}
@Override
public void setUseQuickControls(boolean useQuickControls) {
mUseQuickControls = useQuickControls;
mTitleBar.setUseQuickControls(mUseQuickControls);
if (useQuickControls) {
mPieControl = new PieControlPhone(mActivity, mUiController, this);
mPieControl.attachToContainer(mContentView);
WebView web = getWebView();
if (web != null) {
web.setEmbeddedTitleBar(null);
}
} else {
if (mPieControl != null) {
mPieControl.removeFromContainer(mContentView);
}
WebView web = getWebView();
if (web != null) {
// make sure we can re-parent titlebar
if ((mTitleBar != null) && (mTitleBar.getParent() != null)) {
((ViewGroup) mTitleBar.getParent()).removeView(mTitleBar);
}
web.setEmbeddedTitleBar(mTitleBar);
}
setTitleGravity(Gravity.NO_GRAVITY);
}
updateUrlBarAutoShowManagerTarget();
}
@Override
public boolean isWebShowing() {
return super.isWebShowing() && mNavScreen == null;
}
@Override
public void showWeb(boolean animate) {
super.showWeb(animate);
hideNavScreen(animate);
}
void showNavScreen() {
mUiController.setBlockEvents(true);
mNavScreen = new NavScreen(mActivity, mUiController, this);
mActiveTab.capture();
// Add the custom view to its container
mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
AnimScreen ascreen = new AnimScreen(mActivity, getTitleBar(), getWebView());
final View animView = ascreen.mMain;
mCustomViewContainer.addView(animView, COVER_SCREEN_PARAMS);
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int fromLeft = 0;
int fromTop = getTitleBar().getHeight();
int fromRight = mContentView.getWidth();
int fromBottom = mContentView.getHeight();
int width = target.getWidth();
int height = target.getHeight();
int toLeft = (mContentView.getWidth() - width) / 2;
int toTop = fromTop + (mContentView.getHeight() - fromTop - height) / 2;
int toRight = toLeft + width;
int toBottom = toTop + height;
float scaleFactor = width / (float) mContentView.getWidth();
detachTab(mActiveTab);
mContentView.setVisibility(View.GONE);
AnimatorSet inanim = new AnimatorSet();
ObjectAnimator tx = ObjectAnimator.ofInt(ascreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator ty = ObjectAnimator.ofInt(ascreen.mContent, "top",
fromTop, toTop);
ObjectAnimator tr = ObjectAnimator.ofInt(ascreen.mContent, "right",
fromRight, toRight);
ObjectAnimator tb = ObjectAnimator.ofInt(ascreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator title = ObjectAnimator.ofFloat(ascreen.mTitle, "alpha",
1f, 0f);
ObjectAnimator content = ObjectAnimator.ofFloat(ascreen.mContent, "alpha",
1f, 0f);
ObjectAnimator sx = ObjectAnimator.ofFloat(ascreen, "scaleFactor",
1f, scaleFactor);
inanim.playTogether(tx, ty, tr, tb, title, content, sx);
inanim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(animView);
finishAnimationIn();
mUiController.setBlockEvents(false);
}
});
inanim.setInterpolator(new DecelerateInterpolator(2f));
inanim.setDuration(300);
inanim.start();
}
private void finishAnimationIn() {
if (mNavScreen != null) {
// notify accessibility manager about the screen change
mNavScreen.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mTabControl.setOnThumbnailUpdatedListener(mNavScreen);
}
}
void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
+ if (tab != null) {
+ setActiveTab(tab);
+ } else if (mTabControl.getTabCount() > 0) {
+ // use a fallback tab
+ setActiveTab(mTabControl.getCurrentTab());
+ }
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
+ if (mTabControl.getTabCount() > 0) {
+ // use a fallback tab
+ setActiveTab(mTabControl.getCurrentTab());
+ }
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
private void finishAnimateOut() {
mTabControl.setOnThumbnailUpdatedListener(null);
mCustomViewContainer.removeView(mNavScreen);
mCustomViewContainer.setAlpha(1f);
mNavScreen = null;
mCustomViewContainer.setVisibility(View.GONE);
}
@Override
public boolean needsRestoreAllTabs() {
return false;
}
public void toggleNavScreen() {
if (mNavScreen == null) {
showNavScreen();
} else {
hideNavScreen(false);
}
}
@Override
public boolean shouldCaptureThumbnails() {
return true;
}
static class AnimScreen {
private View mMain;
private ImageView mTitle;
private ImageView mContent;
private float mScale;
public AnimScreen(Context ctx, TitleBar tbar, WebView web) {
mMain = LayoutInflater.from(ctx).inflate(R.layout.anim_screen,
null);
mContent = (ImageView) mMain.findViewById(R.id.content);
mContent.setTop(tbar.getHeight());
mTitle = (ImageView) mMain.findViewById(R.id.title);
Bitmap bm1 = Bitmap.createBitmap(tbar.getWidth(), tbar.getHeight(),
Bitmap.Config.RGB_565);
Canvas c1 = new Canvas(bm1);
tbar.draw(c1);
mTitle.setImageBitmap(bm1);
int h = web.getHeight() - tbar.getHeight();
Bitmap bm2 = Bitmap.createBitmap(web.getWidth(), h,
Bitmap.Config.RGB_565);
Canvas c2 = new Canvas(bm2);
int tx = web.getScrollX();
int ty = web.getScrollY();
c2.translate(-tx, -ty - tbar.getHeight());
web.draw(c2);
mContent.setImageBitmap(bm2);
mContent.setScaleType(ImageView.ScaleType.MATRIX);
mContent.setImageMatrix(new Matrix());
mScale = 1.0f;
setScaleFactor(getScaleFactor());
}
public AnimScreen(Context ctx, Bitmap image) {
mMain = LayoutInflater.from(ctx).inflate(R.layout.anim_screen,
null);
mContent = (ImageView) mMain.findViewById(R.id.content);
mContent.setImageBitmap(image);
mContent.setScaleType(ImageView.ScaleType.MATRIX);
mContent.setImageMatrix(new Matrix());
mScale = 1.0f;
setScaleFactor(getScaleFactor());
}
public void setScaleFactor(float sf) {
mScale = sf;
Matrix m = new Matrix();
m.postScale(sf,sf);
mContent.setImageMatrix(m);
}
public float getScaleFactor() {
return mScale;
}
}
}
| false | true | void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
| void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
if (tab != null) {
setActiveTab(tab);
} else if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
|
diff --git a/src/main/java/ubertweakstor/lagfarmfinder/LagFarmFinder.java b/src/main/java/ubertweakstor/lagfarmfinder/LagFarmFinder.java
index e61028f..859135d 100644
--- a/src/main/java/ubertweakstor/lagfarmfinder/LagFarmFinder.java
+++ b/src/main/java/ubertweakstor/lagfarmfinder/LagFarmFinder.java
@@ -1,121 +1,122 @@
/*
* Author: John "Ubertweakstor" Board
* Date: 21/12/12 14:10
* Description: XRay Detector Plugin
*/
package ubertweakstor.lagfarmfinder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class LagFarmFinder extends JavaPlugin {
static final Logger log = Logger.getLogger("Minecraft");
/*
* Name: onEnable Description: Called when plugin is enabled. Returns: None
* Parameters: None Requirements: None
*/
@Override
public void onEnable() {
log.info("Enabled.");
}
/*
* Name: onDisable Description: Called when plugin is disabled. Returns:
* None Parameters: None Requirements: None
*/
@Override
public void onDisable() {
log.info("Disabled.");
}
// =====[Util]=====//
/*
* Name: onCommand Description: Called when a command has been executed
* Returns: boolean Parameters: CommandSender sender, Command cmd, String
* label, String[] args Requirements: None
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player ply = (Player) sender;
if (label.equalsIgnoreCase("mobcount")){
if (args.length!=2){
ply.sendMessage(ChatColor.RED+"ERROR: Invalid Syntax.");
+ return true;
}
if (getServer().getPlayer(args[0])==null){
ply.sendMessage(ChatColor.RED+"ERROR: Player Not Online");
return true;
}
if(Integer.valueOf(args[1])>200){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
try{
Integer.valueOf(args[1]);
}catch (Exception ex){
ply.sendMessage(ChatColor.RED+"Radius not valid.");
return true;
}
ply.sendMessage(ChatColor.BLUE+"Number of mobs in a "+args[1]+
" radius around "+ChatColor.BLUE+args[0]+": "+
ChatColor.RED+String.valueOf(getNumberOfEntitiesNear(getServer().getPlayer(args[0]), Integer.valueOf(args[1]))));
return true;
} else if(label.equalsIgnoreCase("findlag")){
HashMap<Player, Integer> top = new HashMap<Player, Integer>();
- if(Integer.valueOf(args[0])>200 && args.length==0){
+ if(args.length==1 && Integer.valueOf(args[0])>200){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
for(Player p: getServer().getOnlinePlayers()){
if (args.length >= 1){
top.put(p, getNumberOfEntitiesNear(p, Integer.valueOf(args[0])));
}
else{
top.put(p, getNumberOfEntitiesNear(p, 80));
}
}
int iterations = 0;
if (top.size() > 10){
iterations = 10;
} else {
iterations = top.size();
}
int cnt = 1;
for(int x = 0; x!=iterations; x++){
Map.Entry<Player, Integer> maxEntry = null;
for(Map.Entry<Player, Integer> entry: top.entrySet()){
if (maxEntry == null || entry.getValue()>maxEntry.getValue()){
maxEntry = entry;
}
}
ply.sendMessage(ChatColor.GREEN+String.valueOf(cnt)+
". "+ChatColor.RED+((Player)maxEntry.getKey()).getName()+
": "+ChatColor.BLUE+String.valueOf(maxEntry.getValue()));
top.remove(maxEntry.getKey());
cnt++;
}
}
return true;
}
public int getNumberOfEntitiesNear(Player p, int radius){
try{
return p.getNearbyEntities(radius, radius, radius).size();
} catch (Exception ex){
return -1;
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player ply = (Player) sender;
if (label.equalsIgnoreCase("mobcount")){
if (args.length!=2){
ply.sendMessage(ChatColor.RED+"ERROR: Invalid Syntax.");
}
if (getServer().getPlayer(args[0])==null){
ply.sendMessage(ChatColor.RED+"ERROR: Player Not Online");
return true;
}
if(Integer.valueOf(args[1])>200){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
try{
Integer.valueOf(args[1]);
}catch (Exception ex){
ply.sendMessage(ChatColor.RED+"Radius not valid.");
return true;
}
ply.sendMessage(ChatColor.BLUE+"Number of mobs in a "+args[1]+
" radius around "+ChatColor.BLUE+args[0]+": "+
ChatColor.RED+String.valueOf(getNumberOfEntitiesNear(getServer().getPlayer(args[0]), Integer.valueOf(args[1]))));
return true;
} else if(label.equalsIgnoreCase("findlag")){
HashMap<Player, Integer> top = new HashMap<Player, Integer>();
if(Integer.valueOf(args[0])>200 && args.length==0){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
for(Player p: getServer().getOnlinePlayers()){
if (args.length >= 1){
top.put(p, getNumberOfEntitiesNear(p, Integer.valueOf(args[0])));
}
else{
top.put(p, getNumberOfEntitiesNear(p, 80));
}
}
int iterations = 0;
if (top.size() > 10){
iterations = 10;
} else {
iterations = top.size();
}
int cnt = 1;
for(int x = 0; x!=iterations; x++){
Map.Entry<Player, Integer> maxEntry = null;
for(Map.Entry<Player, Integer> entry: top.entrySet()){
if (maxEntry == null || entry.getValue()>maxEntry.getValue()){
maxEntry = entry;
}
}
ply.sendMessage(ChatColor.GREEN+String.valueOf(cnt)+
". "+ChatColor.RED+((Player)maxEntry.getKey()).getName()+
": "+ChatColor.BLUE+String.valueOf(maxEntry.getValue()));
top.remove(maxEntry.getKey());
cnt++;
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player ply = (Player) sender;
if (label.equalsIgnoreCase("mobcount")){
if (args.length!=2){
ply.sendMessage(ChatColor.RED+"ERROR: Invalid Syntax.");
return true;
}
if (getServer().getPlayer(args[0])==null){
ply.sendMessage(ChatColor.RED+"ERROR: Player Not Online");
return true;
}
if(Integer.valueOf(args[1])>200){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
try{
Integer.valueOf(args[1]);
}catch (Exception ex){
ply.sendMessage(ChatColor.RED+"Radius not valid.");
return true;
}
ply.sendMessage(ChatColor.BLUE+"Number of mobs in a "+args[1]+
" radius around "+ChatColor.BLUE+args[0]+": "+
ChatColor.RED+String.valueOf(getNumberOfEntitiesNear(getServer().getPlayer(args[0]), Integer.valueOf(args[1]))));
return true;
} else if(label.equalsIgnoreCase("findlag")){
HashMap<Player, Integer> top = new HashMap<Player, Integer>();
if(args.length==1 && Integer.valueOf(args[0])>200){
ply.sendMessage(ChatColor.RED+"ERROR: Please do not select a radius higher than 200.");
return true;
}
for(Player p: getServer().getOnlinePlayers()){
if (args.length >= 1){
top.put(p, getNumberOfEntitiesNear(p, Integer.valueOf(args[0])));
}
else{
top.put(p, getNumberOfEntitiesNear(p, 80));
}
}
int iterations = 0;
if (top.size() > 10){
iterations = 10;
} else {
iterations = top.size();
}
int cnt = 1;
for(int x = 0; x!=iterations; x++){
Map.Entry<Player, Integer> maxEntry = null;
for(Map.Entry<Player, Integer> entry: top.entrySet()){
if (maxEntry == null || entry.getValue()>maxEntry.getValue()){
maxEntry = entry;
}
}
ply.sendMessage(ChatColor.GREEN+String.valueOf(cnt)+
". "+ChatColor.RED+((Player)maxEntry.getKey()).getName()+
": "+ChatColor.BLUE+String.valueOf(maxEntry.getValue()));
top.remove(maxEntry.getKey());
cnt++;
}
}
return true;
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/funlib/CompareFunction.java b/src/de/uni_koblenz/jgralab/greql2/funlib/CompareFunction.java
index 3d2c3751a..65620e996 100644
--- a/src/de/uni_koblenz/jgralab/greql2/funlib/CompareFunction.java
+++ b/src/de/uni_koblenz/jgralab/greql2/funlib/CompareFunction.java
@@ -1,106 +1,106 @@
/**
*
*/
package de.uni_koblenz.jgralab.greql2.funlib;
import java.util.ArrayList;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.WrongFunctionParameterException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueType;
/**
* @author Tassilo Horn <[email protected]>
*
*/
public abstract class CompareFunction extends AbstractGreql2Function {
protected enum CompareOperator {
GR_THAN, GR_EQUAL, LE_THAN, LE_EQUAL, NOT_EQUAL
}
{
JValueType[][] x = { { JValueType.NUMBER, JValueType.NUMBER },
{ JValueType.STRING, JValueType.STRING } };
signatures = x;
}
public JValue evaluate(JValue[] arguments, CompareOperator op)
throws EvaluateException {
String s1 = null, s2 = null;
- Double d1 = null, d2 = null;
+ double d1 = 0, d2 = 0;
switch (checkArguments(arguments)) {
case 0:
d1 = arguments[0].toDouble();
d2 = arguments[1].toDouble();
switch (op) {
case GR_EQUAL:
return new JValue(d1 >= d2);
case GR_THAN:
return new JValue(d1 > d2);
case LE_EQUAL:
return new JValue(d1 <= d2);
case LE_THAN:
return new JValue(d1 < d2);
case NOT_EQUAL:
return new JValue(d1 != d2);
}
break;
case 1:
s1 = arguments[0].toString();
s2 = arguments[1].toString();
switch (op) {
case GR_EQUAL:
return new JValue(s1.compareTo(s2) >= 0);
case GR_THAN:
return new JValue(s1.compareTo(s2) == 1);
case LE_EQUAL:
return new JValue(s1.compareTo(s2) <= 0);
case LE_THAN:
return new JValue(s1.compareTo(s2) == -1);
case NOT_EQUAL:
return new JValue(s1.compareTo(s2) != 0);
}
break;
default:
throw new WrongFunctionParameterException(this, null, arguments);
}
throw new EvaluateException("You mustn't come here!");
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.greql2.funlib.Greql2Function#getEstimatedCardinality
* (int)
*/
@Override
public long getEstimatedCardinality(int inElements) {
return 1;
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.greql2.funlib.Greql2Function#getEstimatedCosts
* (java.util.ArrayList)
*/
@Override
public long getEstimatedCosts(ArrayList<Long> inElements) {
return 1;
}
/*
* (non-Javadoc)
*
* @see de.uni_koblenz.jgralab.greql2.funlib.Greql2Function#getSelectivity()
*/
@Override
public double getSelectivity() {
return 0.5;
}
}
| true | true | public JValue evaluate(JValue[] arguments, CompareOperator op)
throws EvaluateException {
String s1 = null, s2 = null;
Double d1 = null, d2 = null;
switch (checkArguments(arguments)) {
case 0:
d1 = arguments[0].toDouble();
d2 = arguments[1].toDouble();
switch (op) {
case GR_EQUAL:
return new JValue(d1 >= d2);
case GR_THAN:
return new JValue(d1 > d2);
case LE_EQUAL:
return new JValue(d1 <= d2);
case LE_THAN:
return new JValue(d1 < d2);
case NOT_EQUAL:
return new JValue(d1 != d2);
}
break;
case 1:
s1 = arguments[0].toString();
s2 = arguments[1].toString();
switch (op) {
case GR_EQUAL:
return new JValue(s1.compareTo(s2) >= 0);
case GR_THAN:
return new JValue(s1.compareTo(s2) == 1);
case LE_EQUAL:
return new JValue(s1.compareTo(s2) <= 0);
case LE_THAN:
return new JValue(s1.compareTo(s2) == -1);
case NOT_EQUAL:
return new JValue(s1.compareTo(s2) != 0);
}
break;
default:
throw new WrongFunctionParameterException(this, null, arguments);
}
throw new EvaluateException("You mustn't come here!");
}
| public JValue evaluate(JValue[] arguments, CompareOperator op)
throws EvaluateException {
String s1 = null, s2 = null;
double d1 = 0, d2 = 0;
switch (checkArguments(arguments)) {
case 0:
d1 = arguments[0].toDouble();
d2 = arguments[1].toDouble();
switch (op) {
case GR_EQUAL:
return new JValue(d1 >= d2);
case GR_THAN:
return new JValue(d1 > d2);
case LE_EQUAL:
return new JValue(d1 <= d2);
case LE_THAN:
return new JValue(d1 < d2);
case NOT_EQUAL:
return new JValue(d1 != d2);
}
break;
case 1:
s1 = arguments[0].toString();
s2 = arguments[1].toString();
switch (op) {
case GR_EQUAL:
return new JValue(s1.compareTo(s2) >= 0);
case GR_THAN:
return new JValue(s1.compareTo(s2) == 1);
case LE_EQUAL:
return new JValue(s1.compareTo(s2) <= 0);
case LE_THAN:
return new JValue(s1.compareTo(s2) == -1);
case NOT_EQUAL:
return new JValue(s1.compareTo(s2) != 0);
}
break;
default:
throw new WrongFunctionParameterException(this, null, arguments);
}
throw new EvaluateException("You mustn't come here!");
}
|
diff --git a/Aufgabe9/Baeckerei.java b/Aufgabe9/Baeckerei.java
index 6efce00..db7e88f 100644
--- a/Aufgabe9/Baeckerei.java
+++ b/Aufgabe9/Baeckerei.java
@@ -1,65 +1,69 @@
import java.util.Iterator;
public class Baeckerei {
private Doppelkeksmaschine dkm;
private Formmaschine fm;
public Baeckerei() {
dkm = new Doppelkeksmaschine();
fm = null;
}
private void set(Formmaschine fm){
this.fm = fm;
}
private Keks einzelBacken(String form, String teig){
setMaschine(form);
return fm.backe(teig);
}
private Keks doppelBacken(String form, String teig, String fuellung){
return dkm.backe(einzelBacken(form, teig), fuellung);
}
private void setMaschine(String form){
if(form.equals("rund")){
set(new Rundmaschine());
}else if( form.equals("mond")){
set(new Mondmaschine());
}else if( form.equals("weihnachtsmann")){
set(new Weihnachtsmannmaschine());
}
}
private boolean validate(Position p){
if(p.getForm() == null || p.getTeig() == null || p.getAnzahl()<1) {
return false;
}
return ((p.getForm().equals("rund") || p.getForm().equals("mond") ||
p.getForm().equals("weihnachtsmann")) && (p.getTeig().equals("muerb")||
p.getTeig().equals("zimtstern")|| p.getTeig().equals("schokolade")) &&
(p.getFuellung() == null || p.getFuellung().equals("marmelade") ||
p.getFuellung().equals("schokolade")));
}
public Keksdose bestellungBearbeiten(Bestellung bestellung){
Keksdose kd = new Keksdose();
Iterator<Position> i = bestellung.iterator();
while(i.hasNext()){
Position p = i.next();
if(!validate(p)){
System.out.println("Ungültige Eingabe in der letzten Bestellung!");
}else{
if(p.getFuellung() != null){
- kd.add(doppelBacken(p.getForm(),p.getTeig(),p.getFuellung()));
+ for(int j = 0; j<p.getAnzahl(); j++){
+ kd.add(doppelBacken(p.getForm(),p.getTeig(),p.getFuellung()));
+ }
}else{
- kd.add(einzelBacken(p.getForm(),p.getTeig()));
+ for(int j = 0; j<p.getAnzahl(); j++){
+ kd.add(einzelBacken(p.getForm(),p.getTeig()));
+ }
}
}
}
return kd;
}
}
| false | true | public Keksdose bestellungBearbeiten(Bestellung bestellung){
Keksdose kd = new Keksdose();
Iterator<Position> i = bestellung.iterator();
while(i.hasNext()){
Position p = i.next();
if(!validate(p)){
System.out.println("Ungültige Eingabe in der letzten Bestellung!");
}else{
if(p.getFuellung() != null){
kd.add(doppelBacken(p.getForm(),p.getTeig(),p.getFuellung()));
}else{
kd.add(einzelBacken(p.getForm(),p.getTeig()));
}
}
}
return kd;
}
| public Keksdose bestellungBearbeiten(Bestellung bestellung){
Keksdose kd = new Keksdose();
Iterator<Position> i = bestellung.iterator();
while(i.hasNext()){
Position p = i.next();
if(!validate(p)){
System.out.println("Ungültige Eingabe in der letzten Bestellung!");
}else{
if(p.getFuellung() != null){
for(int j = 0; j<p.getAnzahl(); j++){
kd.add(doppelBacken(p.getForm(),p.getTeig(),p.getFuellung()));
}
}else{
for(int j = 0; j<p.getAnzahl(); j++){
kd.add(einzelBacken(p.getForm(),p.getTeig()));
}
}
}
}
return kd;
}
|
diff --git a/src/highlevelui/lcdlf/lfjava/classes/com/sun/midp/chameleon/CGraphicsQ.java b/src/highlevelui/lcdlf/lfjava/classes/com/sun/midp/chameleon/CGraphicsQ.java
index b2dff6e3..6c0d0e35 100644
--- a/src/highlevelui/lcdlf/lfjava/classes/com/sun/midp/chameleon/CGraphicsQ.java
+++ b/src/highlevelui/lcdlf/lfjava/classes/com/sun/midp/chameleon/CGraphicsQ.java
@@ -1,131 +1,131 @@
/*
*
*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.midp.chameleon;
import javax.microedition.lcdui.*;
import java.util.Vector;
/**
* Chameleon graphics queue class. This class contains methods
* to help to better control when, how, and how many pixels
* actually get blitted from the buffer to the physical display.
*/
public class CGraphicsQ {
/**
* By turning on "debug" mode, all of Chameleon's graphics engine
* will output tracing info regarding dirty regions, layer locations,
* bounds, repaints, etc.
*/
public static final boolean DEBUG = false;
/** A queue of refresh areas, represented by 4 element arrays */
protected Vector refreshQ;
/**
* Construct a new Graphics queue.
*/
public CGraphicsQ() {
refreshQ = new Vector();
}
/**
* Add the specified region to the queue of areas to be
* refreshed. That is, the region specified by the given
* coordinates represents a region that has been repainted
* and needs to be blitted to the display. The coordinates
* of the region should be in raw screen coordinates, that
* is, 0,0 would represent the topleft pixel on the screen.
*
* @param x the 'x' anchor coordinate of the region
* @param y the 'y' anchor coordinate of the region
* @param w the width of the region
* @param h the height of the region
*/
public void queueRefresh(int x, int y, int w, int h) {
synchronized (refreshQ) {
int[] region;
for (int i = 0; i < refreshQ.size(); i++) {
region = (int[])refreshQ.elementAt(i);
// We test to see if we already have the dirty region
if (region[0] == x && region[1] == y &&
region[2] == w && region[3] == h)
{
return;
}
// We also test to see if the dirty region is wholely
// contained within another region
if (x >= region[0] && y >= region[1] &&
- (x + w) <= (region[0] + region[1]) &&
+ (x + w) <= (region[0] + region[2]) &&
(y + h) <= (region[1] + region[3]))
{
return;
}
// Lastly, we do a special case whereby the region
// is congruent with a previous region. For instance,
// when changing screens, the title area will repaint,
// the body area will repaint, and the soft button
// area will repaint. All 3 areas are congruent and
// can be coalesced.
if (x == region[0] && w == region[2]) {
if ((region[1] + region[3]) == y ||
(y + h) == region[1])
{
if (region[1] > y) {
region[1] = y;
}
region[3] += h;
return;
}
}
}
refreshQ.addElement(new int[] {x, y, w, h});
}
}
/**
* Get the queue of all areas of the screen to be refreshed
* (blitted to the screen). This method will empty the queue
* and return its contents. Each element in the array will be
* a 4 element int[] holding the x, y, w, and h of each refresh
* region
*
* @return the queue of all areas of the screen to be refreshed,
* as an array of arrays
*/
public Object[] getRefreshRegions() {
synchronized (refreshQ) {
Object[] q = new Object[refreshQ.size()];
refreshQ.copyInto(q);
refreshQ.removeAllElements();
return q;
}
}
}
| true | true | public void queueRefresh(int x, int y, int w, int h) {
synchronized (refreshQ) {
int[] region;
for (int i = 0; i < refreshQ.size(); i++) {
region = (int[])refreshQ.elementAt(i);
// We test to see if we already have the dirty region
if (region[0] == x && region[1] == y &&
region[2] == w && region[3] == h)
{
return;
}
// We also test to see if the dirty region is wholely
// contained within another region
if (x >= region[0] && y >= region[1] &&
(x + w) <= (region[0] + region[1]) &&
(y + h) <= (region[1] + region[3]))
{
return;
}
// Lastly, we do a special case whereby the region
// is congruent with a previous region. For instance,
// when changing screens, the title area will repaint,
// the body area will repaint, and the soft button
// area will repaint. All 3 areas are congruent and
// can be coalesced.
if (x == region[0] && w == region[2]) {
if ((region[1] + region[3]) == y ||
(y + h) == region[1])
{
if (region[1] > y) {
region[1] = y;
}
region[3] += h;
return;
}
}
}
refreshQ.addElement(new int[] {x, y, w, h});
}
}
| public void queueRefresh(int x, int y, int w, int h) {
synchronized (refreshQ) {
int[] region;
for (int i = 0; i < refreshQ.size(); i++) {
region = (int[])refreshQ.elementAt(i);
// We test to see if we already have the dirty region
if (region[0] == x && region[1] == y &&
region[2] == w && region[3] == h)
{
return;
}
// We also test to see if the dirty region is wholely
// contained within another region
if (x >= region[0] && y >= region[1] &&
(x + w) <= (region[0] + region[2]) &&
(y + h) <= (region[1] + region[3]))
{
return;
}
// Lastly, we do a special case whereby the region
// is congruent with a previous region. For instance,
// when changing screens, the title area will repaint,
// the body area will repaint, and the soft button
// area will repaint. All 3 areas are congruent and
// can be coalesced.
if (x == region[0] && w == region[2]) {
if ((region[1] + region[3]) == y ||
(y + h) == region[1])
{
if (region[1] > y) {
region[1] = y;
}
region[3] += h;
return;
}
}
}
refreshQ.addElement(new int[] {x, y, w, h});
}
}
|
diff --git a/src/java/org/infoglue/cms/applications/workflowtool/function/ContentMover.java b/src/java/org/infoglue/cms/applications/workflowtool/function/ContentMover.java
index 2c9ccf053..f8261a817 100755
--- a/src/java/org/infoglue/cms/applications/workflowtool/function/ContentMover.java
+++ b/src/java/org/infoglue/cms/applications/workflowtool/function/ContentMover.java
@@ -1,119 +1,119 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.applications.workflowtool.function;
import java.util.Calendar;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentController;
import org.infoglue.cms.entities.content.ContentVO;
import com.opensymphony.workflow.WorkflowException;
/**
*
*
*/
public class ContentMover extends ContentFunction
{
/**
*
*/
public static final String DESTINATION_PARAMETER = "move_newParentFolder";
/**
*
*/
public static final String DESTINATION_PATH_ALGORITHM = "pathAlgorithm";
/**
*
*/
private ContentVO destinationContentVO;
/**
*
*/
public ContentMover()
{
super();
}
/**
*
*/
protected void execute() throws WorkflowException
{
if(getContentVO() != null)
{
try
{
if(!getContentVO().getParentContentId().equals(destinationContentVO.getContentId()))
{
ContentController.getContentController().moveContent(getContentVO(), destinationContentVO.getId(), getDatabase());
}
}
catch(Exception e)
{
throwException(e);
}
}
}
/**
* Method used for initializing the function; will be called before <code>execute</code> is called.
* <p><strong>Note</strong>! You must call <code>super.initialize()</code> first.</p>
*
* 2007-11-05
* Content can now be stored i subfolders of year and month under the designated destination folder.
*
* @throws WorkflowException if an error occurs during the initialization.
*/
protected void initialize() throws WorkflowException
{
super.initialize();
this.destinationContentVO = (ContentVO) getParameter(DESTINATION_PARAMETER, (getContentVO() != null));
if(argumentExists(DESTINATION_PATH_ALGORITHM) && getArgument(DESTINATION_PATH_ALGORITHM).equalsIgnoreCase("YEAR_MONTH"))
{
try
{
String contentPath ="";
Calendar aCal = Calendar.getInstance();
int aYear = aCal.get(Calendar.YEAR);
- int aMonth = aCal.get(Calendar.MONTH + 1);
+ int aMonth = aCal.get(Calendar.MONTH) + 1;
contentPath = ContentController.getContentController().getContentPath(destinationContentVO.getContentId());
contentPath += "/" + aYear +"/" + aMonth;
ContentVO newParentContentVO = ContentController.getContentController().getContentVOWithPath(destinationContentVO.getRepositoryId(), contentPath, true, getPrincipal(), getDatabase());
this.destinationContentVO = newParentContentVO;
}
catch(Exception e)
{
throwException(e);
}
}
}
}
| true | true | protected void initialize() throws WorkflowException
{
super.initialize();
this.destinationContentVO = (ContentVO) getParameter(DESTINATION_PARAMETER, (getContentVO() != null));
if(argumentExists(DESTINATION_PATH_ALGORITHM) && getArgument(DESTINATION_PATH_ALGORITHM).equalsIgnoreCase("YEAR_MONTH"))
{
try
{
String contentPath ="";
Calendar aCal = Calendar.getInstance();
int aYear = aCal.get(Calendar.YEAR);
int aMonth = aCal.get(Calendar.MONTH + 1);
contentPath = ContentController.getContentController().getContentPath(destinationContentVO.getContentId());
contentPath += "/" + aYear +"/" + aMonth;
ContentVO newParentContentVO = ContentController.getContentController().getContentVOWithPath(destinationContentVO.getRepositoryId(), contentPath, true, getPrincipal(), getDatabase());
this.destinationContentVO = newParentContentVO;
}
catch(Exception e)
{
throwException(e);
}
}
}
| protected void initialize() throws WorkflowException
{
super.initialize();
this.destinationContentVO = (ContentVO) getParameter(DESTINATION_PARAMETER, (getContentVO() != null));
if(argumentExists(DESTINATION_PATH_ALGORITHM) && getArgument(DESTINATION_PATH_ALGORITHM).equalsIgnoreCase("YEAR_MONTH"))
{
try
{
String contentPath ="";
Calendar aCal = Calendar.getInstance();
int aYear = aCal.get(Calendar.YEAR);
int aMonth = aCal.get(Calendar.MONTH) + 1;
contentPath = ContentController.getContentController().getContentPath(destinationContentVO.getContentId());
contentPath += "/" + aYear +"/" + aMonth;
ContentVO newParentContentVO = ContentController.getContentController().getContentVOWithPath(destinationContentVO.getRepositoryId(), contentPath, true, getPrincipal(), getDatabase());
this.destinationContentVO = newParentContentVO;
}
catch(Exception e)
{
throwException(e);
}
}
}
|
diff --git a/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/sca/extension/ScaImporterComponent.java b/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/sca/extension/ScaImporterComponent.java
index 6dd3be98..d4f24c46 100644
--- a/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/sca/extension/ScaImporterComponent.java
+++ b/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/sca/extension/ScaImporterComponent.java
@@ -1,145 +1,146 @@
/**
* EasySOA Registry
* Copyright 2011 Open Wide
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact : [email protected]
*/
package org.easysoa.sca.extension;
import java.io.File;
import java.io.InvalidClassException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.easysoa.sca.IScaImporter;
import org.easysoa.sca.visitors.BindingVisitorFactory;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.ComponentName;
import org.nuxeo.runtime.model.DefaultComponent;
/**
*
* @author jguillemotte
*/
public class ScaImporterComponent extends DefaultComponent {
public static final ComponentName NAME = new ComponentName(ComponentName.DEFAULT_TYPE, "org.easysoa.core.service.ScaImporterComponent");
private static Log log = LogFactory.getLog(ScaImporterComponent.class);
private List<Class<?>> scaImporterClasses = new LinkedList<Class<?>>();
public List<Class<?>> getScaImporterClasses() {
return scaImporterClasses;
}
@Override
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception {
log.debug("registering contribution ..." + extensionPoint);
try {
synchronized (scaImporterClasses) {
if (extensionPoint.equals("scaImporters")) {
ScaImporterDescriptor scaImporterDescriptor = (ScaImporterDescriptor) contribution;
checkAndSetScaImporter(scaImporterDescriptor, contributor);
}
}
} catch (Exception ex) {
log.error("registrerContribution error : " + ex.getMessage());
throw new Exception(renderContributionError(contributor, ""), ex);
}
}
@Override
public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
synchronized (scaImporterClasses) {
if (extensionPoint.equals("scaImporters")) {
ScaImporterDescriptor scaImporterDescriptor = (ScaImporterDescriptor) contribution;
if (scaImporterDescriptor.enabled) {
try {
Class<?> scaImporterClass = Class.forName(scaImporterDescriptor.implementation.trim());
- for (Class<?> currentScaImporterClass : scaImporterClasses) {
+ List<Class<?>> scaImporterClassesCopy = new LinkedList<Class<?>>(scaImporterClasses);
+ for (Class<?> currentScaImporterClass : scaImporterClassesCopy) {
if (currentScaImporterClass.equals(scaImporterClass)) {
scaImporterClasses.remove(scaImporterClass);
}
}
} catch (Exception ex) {
log.warn("Failed to unregister contribution: " + ex.getMessage());
}
}
}
}
}
/**
* Check that the impl has the required constructor
*
* @param scaImporterDescriptor
* @param contributor
* @throws Exception
*/
public void checkAndSetScaImporter(ScaImporterDescriptor scaImporterDescriptor, ComponentInstance contributor) throws Exception {
if (scaImporterDescriptor.enabled) {
Class<?> scaImporterClass = Class.forName(scaImporterDescriptor.implementation.trim());
log.debug("scaImporterClass = " + scaImporterClass);
if (IScaImporter.class.isAssignableFrom(scaImporterClass)) {
// trying to create one in order to check that the impl has the
// required constructor
log.debug("scaImporterClass = " + scaImporterClass.getName());
scaImporterClass.getConstructor(new Class[] { BindingVisitorFactory.class, File.class })
.newInstance(new Object[] { null, null });
this.scaImporterClasses.add(scaImporterClass);
} else {
log.debug("Check and set Sca importer error");
throw new InvalidClassException(renderContributionError(contributor, "class " + scaImporterDescriptor.implementation + " is not an instance of " + IScaImporter.class.getName()));
}
}
}
/**
* Creates a SCA Importer
*
* @param bindingVisitorFactory The binding factory to use
* @param compositeFile The composite file to parse/discover
* @return A <code>IScaImporter</code>
*/
public IScaImporter createScaImporter(BindingVisitorFactory bindingVisitorFactory, File compositeFile) {
try {
log.debug("scaImporterClasses.size() = " + scaImporterClasses.size());
Class<?> scaImporterClass = this.scaImporterClasses.get(scaImporterClasses.size() - 1);
return (IScaImporter) scaImporterClass.getConstructor(new Class[] { BindingVisitorFactory.class, File.class })
.newInstance(new Object[] { bindingVisitorFactory, compositeFile });
} catch (Exception ex) {
log.error("An error occurs during the creation of SCA importer", ex);
// TODO log "error creating sca import, bad config, see init logs"
}
return null;
}
/**
* Render a contributor error
*
* @param contributor a <code>ComponentInstance</code>
* @param message The error message to add at the end of the contribution error
* @return A contribution error message
*/
private String renderContributionError(ComponentInstance contributor, String message) {
return "Invalid contribution from '" + contributor.getName() + "': " + message;
}
}
| true | true | public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
synchronized (scaImporterClasses) {
if (extensionPoint.equals("scaImporters")) {
ScaImporterDescriptor scaImporterDescriptor = (ScaImporterDescriptor) contribution;
if (scaImporterDescriptor.enabled) {
try {
Class<?> scaImporterClass = Class.forName(scaImporterDescriptor.implementation.trim());
for (Class<?> currentScaImporterClass : scaImporterClasses) {
if (currentScaImporterClass.equals(scaImporterClass)) {
scaImporterClasses.remove(scaImporterClass);
}
}
} catch (Exception ex) {
log.warn("Failed to unregister contribution: " + ex.getMessage());
}
}
}
}
}
| public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
synchronized (scaImporterClasses) {
if (extensionPoint.equals("scaImporters")) {
ScaImporterDescriptor scaImporterDescriptor = (ScaImporterDescriptor) contribution;
if (scaImporterDescriptor.enabled) {
try {
Class<?> scaImporterClass = Class.forName(scaImporterDescriptor.implementation.trim());
List<Class<?>> scaImporterClassesCopy = new LinkedList<Class<?>>(scaImporterClasses);
for (Class<?> currentScaImporterClass : scaImporterClassesCopy) {
if (currentScaImporterClass.equals(scaImporterClass)) {
scaImporterClasses.remove(scaImporterClass);
}
}
} catch (Exception ex) {
log.warn("Failed to unregister contribution: " + ex.getMessage());
}
}
}
}
}
|
diff --git a/src/no/ntnu/stud/flatcraft/entities/Player.java b/src/no/ntnu/stud/flatcraft/entities/Player.java
index 480ec69..12e2d66 100644
--- a/src/no/ntnu/stud/flatcraft/entities/Player.java
+++ b/src/no/ntnu/stud/flatcraft/entities/Player.java
@@ -1,181 +1,181 @@
package no.ntnu.stud.flatcraft.entities;
import net.phys2d.math.Vector2f;
import net.phys2d.raw.Body;
import no.ntnu.stud.flatcraft.GameWorld;
import no.ntnu.stud.flatcraft.Main;
import no.ntnu.stud.flatcraft.quadtree.Block;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Line;
import org.newdawn.slick.state.StateBasedGame;
public class Player {
Character character;
Vector2f fireVector;
Inventory inventory;
private Vector2f startPosition;
private boolean blockSelected = false;
public Player(GameWorld gw, float _x, float _y, float _width,
float _height, float _mass) {
startPosition = new Vector2f(_x, _y);
character = new Character(gw, _x, _y, _width, _height, _mass);
respawn();
fireVector = new Vector2f(0, 0);
inventory = new Inventory();
}
public void reset() {
character.spawn(new Vector2f(startPosition.getX(), startPosition.getY()));
}
public void render(Graphics g) {
g.pushTransform();
g.translate(-character.gameworld.viewport.getX(),
-character.gameworld.viewport.getY());
g.draw(new Line(character.boundingBox.getCenterX(),
character.boundingBox.getCenterY(), character.boundingBox
.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()));
g.popTransform();
inventory.render(g);
}
public void respawn() {
character.spawn(new Vector2f(Main.GU * 10, Main.GU * 10)); // Test
// numbers,
// should
// ask for
// spawn
// locations
}
public void update(GameContainer container, StateBasedGame game, int delta) {
if (Main.KEYDOWN[Input.KEY_Q] && !blockSelected) {
inventory.prev();
blockSelected = true;
}
if (Main.KEYDOWN[Input.KEY_E] && !blockSelected) {
inventory.next();
blockSelected = true;
}
if (!Main.KEYDOWN[Input.KEY_Q] && !Main.KEYDOWN[Input.KEY_E] && blockSelected) {
blockSelected = false;
}
if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]
|| Main.KEYDOWN[Input.KEY_SPACE]) {
if (character.grounded) {
character.applyForce(0, -Main.GU * 1600f);
}
- }
+ }
if (Main.KEYDOWN[Input.KEY_LEFT] || Main.KEYDOWN[Input.KEY_A]) {
character.applyForce(-Main.GU * 200, 0);
}
if (Main.KEYDOWN[Input.KEY_RIGHT] || Main.KEYDOWN[Input.KEY_D]) {
character.applyForce(Main.GU * 200, 0);
}
// if (Main.KEYDOWN[Input.KEY_DOWN] || Main.KEYDOWN[Input.KEY_S]) {
// character.body.addForce((new Vector2f(0, Main.GU * 1000)));
// }
// if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]) {
// character.body.addForce((new Vector2f(0, -Main.GU * 1000)));
// }
if (Main.MOUSEDOWN[0]) {
// character.gameworld.terrain.fillCell(Main.MOUSEX+character.gameworld.viewport.getX(),
// Main.MOUSEY+character.gameworld.viewport.getY(),activeBlock);
Block out = inventory.peek();
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
if (out != null && character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type == Block.EMPTY) {
inventory.pop();
character.gameworld.terrain.fillCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY(),
out);
}
}
if (Main.MOUSEDOWN[1]) {
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
switch (character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type) {
case ROCK:
case RUBBER:
case WATER:
inventory.push(character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type);
case EARTH:
character.gameworld.terrain.emptyCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY());
break;
default:
break;
}
}
if (character.body.getPosition().getY() > Main.GU * 48
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
if (character.body.getPosition().getY() < Main.GU * 16
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 16));
}
if (character.body.getPosition().getX() > Main.GU * 100
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 100,
character.gameworld.getViewportPosition().getY()));
}
if (character.body.getPosition().getX() < Main.GU * 16
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 16,
character.gameworld.getViewportPosition().getY()));
}
if (character.grounded) {
// tween this
character.gameworld.setViewportPositionGoal(new Vector2f(
- character.gameworld.getViewportPosition().getX(),
+ character.gameworld.viewportgoal.getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
}
public Character getCharacter() {
return character;
}
public Body getBody() {
return character.body;
}
}
| false | true | public void update(GameContainer container, StateBasedGame game, int delta) {
if (Main.KEYDOWN[Input.KEY_Q] && !blockSelected) {
inventory.prev();
blockSelected = true;
}
if (Main.KEYDOWN[Input.KEY_E] && !blockSelected) {
inventory.next();
blockSelected = true;
}
if (!Main.KEYDOWN[Input.KEY_Q] && !Main.KEYDOWN[Input.KEY_E] && blockSelected) {
blockSelected = false;
}
if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]
|| Main.KEYDOWN[Input.KEY_SPACE]) {
if (character.grounded) {
character.applyForce(0, -Main.GU * 1600f);
}
}
if (Main.KEYDOWN[Input.KEY_LEFT] || Main.KEYDOWN[Input.KEY_A]) {
character.applyForce(-Main.GU * 200, 0);
}
if (Main.KEYDOWN[Input.KEY_RIGHT] || Main.KEYDOWN[Input.KEY_D]) {
character.applyForce(Main.GU * 200, 0);
}
// if (Main.KEYDOWN[Input.KEY_DOWN] || Main.KEYDOWN[Input.KEY_S]) {
// character.body.addForce((new Vector2f(0, Main.GU * 1000)));
// }
// if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]) {
// character.body.addForce((new Vector2f(0, -Main.GU * 1000)));
// }
if (Main.MOUSEDOWN[0]) {
// character.gameworld.terrain.fillCell(Main.MOUSEX+character.gameworld.viewport.getX(),
// Main.MOUSEY+character.gameworld.viewport.getY(),activeBlock);
Block out = inventory.peek();
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
if (out != null && character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type == Block.EMPTY) {
inventory.pop();
character.gameworld.terrain.fillCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY(),
out);
}
}
if (Main.MOUSEDOWN[1]) {
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
switch (character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type) {
case ROCK:
case RUBBER:
case WATER:
inventory.push(character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type);
case EARTH:
character.gameworld.terrain.emptyCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY());
break;
default:
break;
}
}
if (character.body.getPosition().getY() > Main.GU * 48
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
if (character.body.getPosition().getY() < Main.GU * 16
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 16));
}
if (character.body.getPosition().getX() > Main.GU * 100
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 100,
character.gameworld.getViewportPosition().getY()));
}
if (character.body.getPosition().getX() < Main.GU * 16
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 16,
character.gameworld.getViewportPosition().getY()));
}
if (character.grounded) {
// tween this
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
}
| public void update(GameContainer container, StateBasedGame game, int delta) {
if (Main.KEYDOWN[Input.KEY_Q] && !blockSelected) {
inventory.prev();
blockSelected = true;
}
if (Main.KEYDOWN[Input.KEY_E] && !blockSelected) {
inventory.next();
blockSelected = true;
}
if (!Main.KEYDOWN[Input.KEY_Q] && !Main.KEYDOWN[Input.KEY_E] && blockSelected) {
blockSelected = false;
}
if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]
|| Main.KEYDOWN[Input.KEY_SPACE]) {
if (character.grounded) {
character.applyForce(0, -Main.GU * 1600f);
}
}
if (Main.KEYDOWN[Input.KEY_LEFT] || Main.KEYDOWN[Input.KEY_A]) {
character.applyForce(-Main.GU * 200, 0);
}
if (Main.KEYDOWN[Input.KEY_RIGHT] || Main.KEYDOWN[Input.KEY_D]) {
character.applyForce(Main.GU * 200, 0);
}
// if (Main.KEYDOWN[Input.KEY_DOWN] || Main.KEYDOWN[Input.KEY_S]) {
// character.body.addForce((new Vector2f(0, Main.GU * 1000)));
// }
// if (Main.KEYDOWN[Input.KEY_UP] || Main.KEYDOWN[Input.KEY_W]) {
// character.body.addForce((new Vector2f(0, -Main.GU * 1000)));
// }
if (Main.MOUSEDOWN[0]) {
// character.gameworld.terrain.fillCell(Main.MOUSEX+character.gameworld.viewport.getX(),
// Main.MOUSEY+character.gameworld.viewport.getY(),activeBlock);
Block out = inventory.peek();
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
if (out != null && character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type == Block.EMPTY) {
inventory.pop();
character.gameworld.terrain.fillCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY(),
out);
}
}
if (Main.MOUSEDOWN[1]) {
fireVector.set(Main.MOUSEX + character.gameworld.viewport.getX()
- character.boundingBox.getCenterX(), Main.MOUSEY
+ character.gameworld.viewport.getY()
- character.boundingBox.getCenterY());
fireVector.normalise();
fireVector.scale(Main.GU * 6);
switch (character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type) {
case ROCK:
case RUBBER:
case WATER:
inventory.push(character.gameworld.terrain.getLeaf(character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY()).type);
case EARTH:
character.gameworld.terrain.emptyCell(
character.boundingBox.getCenterX() + fireVector.getX(),
character.boundingBox.getCenterY() + fireVector.getY());
break;
default:
break;
}
}
if (character.body.getPosition().getY() > Main.GU * 48
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
if (character.body.getPosition().getY() < Main.GU * 16
+ character.gameworld.getViewportPosition().getY()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.getViewportPosition().getX(),
character.body.getPosition().getY() - Main.GU * 16));
}
if (character.body.getPosition().getX() > Main.GU * 100
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 100,
character.gameworld.getViewportPosition().getY()));
}
if (character.body.getPosition().getX() < Main.GU * 16
+ character.gameworld.getViewportPosition().getX()) {
character.gameworld.setViewportPositionGoal(new Vector2f(
character.body.getPosition().getX() - Main.GU * 16,
character.gameworld.getViewportPosition().getY()));
}
if (character.grounded) {
// tween this
character.gameworld.setViewportPositionGoal(new Vector2f(
character.gameworld.viewportgoal.getX(),
character.body.getPosition().getY() - Main.GU * 48));
}
}
|
diff --git a/rqdql/src/main/java/com/rqdql/Log.java b/rqdql/src/main/java/com/rqdql/Log.java
index 67da0e8b..a6c6745e 100644
--- a/rqdql/src/main/java/com/rqdql/Log.java
+++ b/rqdql/src/main/java/com/rqdql/Log.java
@@ -1,171 +1,171 @@
/**
* RQDQL.com
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt. It is also available
* through the world-wide-web at this URL: http://www.rqdql.com/LICENSE.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package com.rqdql;
// for internal logging
import org.apache.log4j.Logger;
/**
* Globall logger, very convenient to use.
*
* <p>Use it like this in any class, and in any package:
*
* <pre>
* {@code
* package com.rqdql.XXX;
* import com.rqdql.Log;
* public class MyClass {
* public void foo() {
* Log.debug("The method foo() was just called");
* }
* }
* [...]
* }
* </pre>
*
* <p>There is some discussion at
* <a href="http://stackoverflow.com/questions/4106324">StackOverflow</a>
* about this idea.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
*/
public final class Log {
/**
* Private ctor, to avoid a possibility to instantiate this
* class directly.
*/
private Log() {
// intentionally empty
}
/**
* Protocol one information message, through
* a global {@link Logger}. This is just
* a static wrapper of a non-static method of a {@link Logger}
* class.
*
* @param msg The message to protocol
* @param args Vararg list of params
*/
public static void info(
final String msg,
final Object... args) {
Log.logger().info(Log.compose(msg, args));
}
/**
* Protocol one information message, through
* a global {@link Logger}. This is just
* a static wrapper of a non-static method of a {@link Logger}
* class.
*
* @param msg The message to protocol
* @param args Vararg list of params
*/
public static void debug(
final String msg,
final Object... args) {
Log.logger().debug(Log.compose(msg, args));
}
/**
* Protocol one information message, through
* a global {@link Logger}. This is just
* a static wrapper of a non-static method of a {@link Logger}
* class.
*
* @param msg The message to protocol
* @param args Vararg list of params
*/
public static void warn(
final String msg,
final Object... args) {
Log.logger().warn(Log.compose(msg, args));
}
/**
* Protocol one information message, through
* a global {@link Logger}. This is just
* a static wrapper of a non-static method of a {@link Logger}
* class.
*
* @param msg The message to protocol
* @param args Vararg list of params
*/
public static void error(
final String msg,
final Object... args) {
Log.logger().error(Log.compose(msg, args));
}
/**
* Protocol one information message, through
* a global {@link Logger}. This is just
* a static wrapper of a non-static method of a {@link Logger}
* class.
*
* @param msg The message to protocol
* @param args Vararg list of params
*/
public static void trace(
final String msg,
final Object... args) {
Log.logger().trace(Log.compose(msg, args));
}
/**
* Get the instance of the logger for this particular caller.
*
* <p>Here we retrieve the name of calling class from stack trace,
* using the third position in it.
*
* @return The instance of {@link Logger} class
*/
private static Logger logger() {
- final Throwable thr = new Throwable() { };
+ final Throwable thr = new NullPointerException();
final StackTraceElement[] elements = thr.getStackTrace();
String name = Log.class.getCanonicalName();
for (int idx = 2; idx < elements.length; idx += 1) {
name = elements[idx].getClassName();
if (name.startsWith("com.rqdql.")) {
break;
}
}
return Logger.getLogger(name);
}
/**
* Compose a message using varargs.
*
* @param msg The message
* @param args List of args
* @return The message composed
*/
private static String compose(final String msg, final Object[] args) {
return String.format(msg, args);
}
}
| true | true | private static Logger logger() {
final Throwable thr = new Throwable() { };
final StackTraceElement[] elements = thr.getStackTrace();
String name = Log.class.getCanonicalName();
for (int idx = 2; idx < elements.length; idx += 1) {
name = elements[idx].getClassName();
if (name.startsWith("com.rqdql.")) {
break;
}
}
return Logger.getLogger(name);
}
| private static Logger logger() {
final Throwable thr = new NullPointerException();
final StackTraceElement[] elements = thr.getStackTrace();
String name = Log.class.getCanonicalName();
for (int idx = 2; idx < elements.length; idx += 1) {
name = elements[idx].getClassName();
if (name.startsWith("com.rqdql.")) {
break;
}
}
return Logger.getLogger(name);
}
|
diff --git a/ttools/src/testcases/uk/ac/starlink/ttools/cone/LinearConeSearcher.java b/ttools/src/testcases/uk/ac/starlink/ttools/cone/LinearConeSearcher.java
index dc8f9861f..e6d60082d 100644
--- a/ttools/src/testcases/uk/ac/starlink/ttools/cone/LinearConeSearcher.java
+++ b/ttools/src/testcases/uk/ac/starlink/ttools/cone/LinearConeSearcher.java
@@ -1,74 +1,75 @@
package uk.ac.starlink.ttools.cone;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.DefaultValueInfo;
import uk.ac.starlink.table.RowListStarTable;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.Tables;
import uk.ac.starlink.table.ValueInfo;
import uk.ac.starlink.task.Environment;
import uk.ac.starlink.task.Parameter;
/**
* Test ConeSearcher implementation. Each cone search returns objects
* at the same
* RA as the request but at a variety of Decs. A fixed number of results
* within and without the area is returned.
*/
public class LinearConeSearcher implements ConeSearcher {
private final int nIn_;
private final int nOut_;
private static final ValueInfo ID_INFO =
new DefaultValueInfo( "ID", Integer.class );
/**
* Constructor.
*
* @param nIn number of results at each point within search radius
* @param nOut number of results at each point without search radius
* (this is permitted by contract)
*/
public LinearConeSearcher( int nIn, int nOut ) {
nIn_ = nIn;
nOut_ = nOut;
}
public int getRaIndex( StarTable result ) {
return 1;
}
public int getDecIndex( StarTable result ) {
return 2;
}
public StarTable performSearch( double ra, double dec, double sr ) {
List rowList = new ArrayList();
for ( int i = 0; i < nIn_; i++ ) {
rowList.add( new Object[] { new Integer( i + 1 ),
new Double( ra ),
- new Double( dec + sr / nIn_ ) } );
+ new Double( dec + sr * i / nIn_ ) } );
}
for ( int i = 0; i < nOut_; i++ ) {
rowList.add( new Object[] { new Integer( - i - 1 ),
new Double( ra ),
- new Double( dec + sr + sr / nOut_ ) } );
+ new Double( dec + sr * 1.01
+ + sr * i / nOut_ ) } );
}
Collections.shuffle( rowList );
RowListStarTable table =
new RowListStarTable( new ColumnInfo[] {
new ColumnInfo( ID_INFO ),
new ColumnInfo( Tables.RA_INFO ),
new ColumnInfo( Tables.DEC_INFO ), } );
for ( Iterator it = rowList.iterator(); it.hasNext(); ) {
table.addRow( (Object[]) it.next() );
}
return table;
}
}
| false | true | public StarTable performSearch( double ra, double dec, double sr ) {
List rowList = new ArrayList();
for ( int i = 0; i < nIn_; i++ ) {
rowList.add( new Object[] { new Integer( i + 1 ),
new Double( ra ),
new Double( dec + sr / nIn_ ) } );
}
for ( int i = 0; i < nOut_; i++ ) {
rowList.add( new Object[] { new Integer( - i - 1 ),
new Double( ra ),
new Double( dec + sr + sr / nOut_ ) } );
}
Collections.shuffle( rowList );
RowListStarTable table =
new RowListStarTable( new ColumnInfo[] {
new ColumnInfo( ID_INFO ),
new ColumnInfo( Tables.RA_INFO ),
new ColumnInfo( Tables.DEC_INFO ), } );
for ( Iterator it = rowList.iterator(); it.hasNext(); ) {
table.addRow( (Object[]) it.next() );
}
return table;
}
| public StarTable performSearch( double ra, double dec, double sr ) {
List rowList = new ArrayList();
for ( int i = 0; i < nIn_; i++ ) {
rowList.add( new Object[] { new Integer( i + 1 ),
new Double( ra ),
new Double( dec + sr * i / nIn_ ) } );
}
for ( int i = 0; i < nOut_; i++ ) {
rowList.add( new Object[] { new Integer( - i - 1 ),
new Double( ra ),
new Double( dec + sr * 1.01
+ sr * i / nOut_ ) } );
}
Collections.shuffle( rowList );
RowListStarTable table =
new RowListStarTable( new ColumnInfo[] {
new ColumnInfo( ID_INFO ),
new ColumnInfo( Tables.RA_INFO ),
new ColumnInfo( Tables.DEC_INFO ), } );
for ( Iterator it = rowList.iterator(); it.hasNext(); ) {
table.addRow( (Object[]) it.next() );
}
return table;
}
|
diff --git a/core/src/test/java/org/mule/ibeans/IBeansHolderConfigBuilderTestCase.java b/core/src/test/java/org/mule/ibeans/IBeansHolderConfigBuilderTestCase.java
index 84721a0..1c619b1 100644
--- a/core/src/test/java/org/mule/ibeans/IBeansHolderConfigBuilderTestCase.java
+++ b/core/src/test/java/org/mule/ibeans/IBeansHolderConfigBuilderTestCase.java
@@ -1,45 +1,45 @@
/*
* $Id$
* --------------------------------------------------------------------------------------
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.ibeans;
import org.mule.ibeans.config.IBeanHolder;
import org.mule.ibeans.config.IBeanHolderConfigurationBuilder;
import org.mule.ibeans.test.AbstractIBeansTestCase;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class IBeansHolderConfigBuilderTestCase extends AbstractIBeansTestCase
{
public void testConfigBuilder() throws Exception
{
IBeanHolderConfigurationBuilder builder = new IBeanHolderConfigurationBuilder();
builder.configure(muleContext);
Collection<IBeanHolder> col = muleContext.getRegistry().lookupObjects(IBeanHolder.class);
//Ensure IBeanHolder is comarable
Set<IBeanHolder> beans = new TreeSet<IBeanHolder>(col);
assertEquals(5, beans.size());
String[] ids = new String[5];
int i = 0;
for (Iterator<IBeanHolder> iterator = beans.iterator(); iterator.hasNext(); i++)
{
IBeanHolder iBeanHolder = iterator.next();
ids[i] = iBeanHolder.getId();
}
- assertEquals("returnexpressions", ids[0]);
+ assertEquals("search", ids[0]);
assertEquals("testexception", ids[1]);
assertEquals("testimplicitpropertiesinfactory", ids[2]);
assertEquals("testparamsfactory", ids[3]);
assertEquals("testuri", ids[4]);
}
}
| true | true | public void testConfigBuilder() throws Exception
{
IBeanHolderConfigurationBuilder builder = new IBeanHolderConfigurationBuilder();
builder.configure(muleContext);
Collection<IBeanHolder> col = muleContext.getRegistry().lookupObjects(IBeanHolder.class);
//Ensure IBeanHolder is comarable
Set<IBeanHolder> beans = new TreeSet<IBeanHolder>(col);
assertEquals(5, beans.size());
String[] ids = new String[5];
int i = 0;
for (Iterator<IBeanHolder> iterator = beans.iterator(); iterator.hasNext(); i++)
{
IBeanHolder iBeanHolder = iterator.next();
ids[i] = iBeanHolder.getId();
}
assertEquals("returnexpressions", ids[0]);
assertEquals("testexception", ids[1]);
assertEquals("testimplicitpropertiesinfactory", ids[2]);
assertEquals("testparamsfactory", ids[3]);
assertEquals("testuri", ids[4]);
}
| public void testConfigBuilder() throws Exception
{
IBeanHolderConfigurationBuilder builder = new IBeanHolderConfigurationBuilder();
builder.configure(muleContext);
Collection<IBeanHolder> col = muleContext.getRegistry().lookupObjects(IBeanHolder.class);
//Ensure IBeanHolder is comarable
Set<IBeanHolder> beans = new TreeSet<IBeanHolder>(col);
assertEquals(5, beans.size());
String[] ids = new String[5];
int i = 0;
for (Iterator<IBeanHolder> iterator = beans.iterator(); iterator.hasNext(); i++)
{
IBeanHolder iBeanHolder = iterator.next();
ids[i] = iBeanHolder.getId();
}
assertEquals("search", ids[0]);
assertEquals("testexception", ids[1]);
assertEquals("testimplicitpropertiesinfactory", ids[2]);
assertEquals("testparamsfactory", ids[3]);
assertEquals("testuri", ids[4]);
}
|
diff --git a/src/plugins/WoT/Trust.java b/src/plugins/WoT/Trust.java
index 3154da0a..0daa2776 100644
--- a/src/plugins/WoT/Trust.java
+++ b/src/plugins/WoT/Trust.java
@@ -1,165 +1,166 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WoT;
import java.util.Date;
import freenet.support.CurrentTimeUTC;
import plugins.WoT.exceptions.InvalidParameterException;
/**
* A trust relationship between two Identities.
*
* @author xor ([email protected])
* @author Julien Cornuwel ([email protected])
*/
public final class Trust {
public static final int MAX_TRUST_COMMENT_LENGTH = 256;
/** The identity which gives the trust. */
private final Identity mTruster;
/** The identity which receives the trust. */
private final Identity mTrustee;
/** The value assigned with the trust, from -100 to +100 where negative means distrust */
private byte mValue;
/** An explanation of why the trust value was assigned */
private String mComment;
/**
* The date when this trust value was assigned.
*/
private Date mLastChangedDate;
/**
* The edition number of the trust list in which this trust was published the last time.
* This is used to speed up the import of new trust lists: When importing them, we need to delete removed trust values. We cannot just
* delete all trust values of the truster from the database and then import the trust list because deleting a trust causes recalculation
* of the score of the trustee. So for trust values which were not really removed from the trust list we would recalculate the score twice:
* One time when the old trust object is deleted and one time when the new trust is imported. Not only that we might recalculate one
* time without any necessity, most of the time even any recalculation would not be needed because the trust value has not changed.
*
* To prevent this, we do the following: When creating new trusts, we store the edition number of the trust list from which we obtained it.
* When importing a new trust list, for each trust value we query the database whether a trust value to this trustee already exists and
* update it if it does - we also update the trust list edition member variable. After having imported all trust values we query the
* database for trust objects from the truster which have an old trust list edition number and delete them - the old edition number
* means that the trust has been removed from the latest trust list.
*/
@SuppressWarnings("unused")
private long mTrusterTrustListEdition;
/**
* Get a list of fields which the database should create an index on.
*/
protected static String[] getIndexedFields() {
return new String[] { "mTruster", "mTrustee" };
}
/**
* Creates a Trust from given parameters. Only for being used by the WoT package and unit tests, not for user interfaces!
*
* @param truster Identity that gives the trust
* @param trustee Identity that receives the trust
* @param value Numeric value of the Trust
* @param comment A comment to explain the numeric trust value
* @throws InvalidParameterException if the trust value is not between -100 and +100
*/
public Trust(Identity truster, Identity trustee, byte value, String comment) throws InvalidParameterException {
if(truster == null)
throw new NullPointerException();
if(trustee == null)
throw new NullPointerException();
mTruster = truster;
mTrustee = trustee;
setValue(value);
+ mComment = ""; // Simplify setComment
setComment(comment);
- mLastChangedDate = CurrentTimeUTC.get();
+ // mLastChangedDate = CurrentTimeUTC.get(); // Done by setValue / setComment.
mTrusterTrustListEdition = truster.getEdition();
}
@Override
public synchronized String toString() {
return getTruster().getNickname() + " trusts " + getTrustee().getNickname() + " with value " + getValue() + " (comment: " + getComment() + ")";
}
/** @return The Identity that gives this trust. */
public Identity getTruster() {
return mTruster;
}
/** @return The Identity that receives this trust. */
public Identity getTrustee() {
return mTrustee;
}
/** @return value Numeric value of this trust relationship. The allowed range is -100 to +100, including both limits. 0 counts as positive. */
public synchronized byte getValue() {
return mValue;
}
/**
* @param mValue Numeric value of this trust relationship. The allowed range is -100 to +100, including both limits. 0 counts as positive.
* @throws InvalidParameterException if value isn't in the range
*/
protected synchronized void setValue(byte newValue) throws InvalidParameterException {
if(newValue < -100 || newValue > 100)
throw new InvalidParameterException("Invalid trust value ("+ newValue +"). Trust values must be in range of -100 to +100.");
if(mValue != newValue) {
mValue = newValue;
mLastChangedDate = CurrentTimeUTC.get();
}
}
/** @return The comment associated to this Trust relationship. */
public synchronized String getComment() {
return mComment;
}
/**
* @param newComment Comment on this trust relationship.
*/
protected synchronized void setComment(String newComment) throws InvalidParameterException {
assert(newComment != null);
if(newComment != null && newComment.length() > MAX_TRUST_COMMENT_LENGTH)
throw new InvalidParameterException("Comment is too long (maximum is " + MAX_TRUST_COMMENT_LENGTH + " characters).");
newComment = newComment != null ? newComment : "";
if(!mComment.equals(newComment)) {
mComment = newComment;
mLastChangedDate = CurrentTimeUTC.get();
}
}
public synchronized Date getDateOfLastChange() {
return mLastChangedDate;
}
/**
* Only for being used in upgradeDatabase(). FIXME: Remove before release.
*/
public synchronized void setDateOfLastChange(Date date) {
mLastChangedDate = date;
}
/**
* Called by the XMLTransformer when a new trust list of the truster has been imported. Stores the edition number of the trust list in this trust object.
* For an explanation for what this is needed please read the description of {@link mTrusterTrustListEdition}.
*/
protected synchronized void trusterEditionUpdated() {
mTrusterTrustListEdition = mTruster.getEdition();
}
}
| false | true | public Trust(Identity truster, Identity trustee, byte value, String comment) throws InvalidParameterException {
if(truster == null)
throw new NullPointerException();
if(trustee == null)
throw new NullPointerException();
mTruster = truster;
mTrustee = trustee;
setValue(value);
setComment(comment);
mLastChangedDate = CurrentTimeUTC.get();
mTrusterTrustListEdition = truster.getEdition();
}
| public Trust(Identity truster, Identity trustee, byte value, String comment) throws InvalidParameterException {
if(truster == null)
throw new NullPointerException();
if(trustee == null)
throw new NullPointerException();
mTruster = truster;
mTrustee = trustee;
setValue(value);
mComment = ""; // Simplify setComment
setComment(comment);
// mLastChangedDate = CurrentTimeUTC.get(); // Done by setValue / setComment.
mTrusterTrustListEdition = truster.getEdition();
}
|
diff --git a/test/org/apache/pig/impl/builtin/TestStreamingUDF.java b/test/org/apache/pig/impl/builtin/TestStreamingUDF.java
index 87301acd..92e57b74 100644
--- a/test/org/apache/pig/impl/builtin/TestStreamingUDF.java
+++ b/test/org/apache/pig/impl/builtin/TestStreamingUDF.java
@@ -1,303 +1,303 @@
package org.apache.pig.impl.builtin;
import static org.apache.pig.builtin.mock.Storage.resetData;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.builtin.mock.Storage.Data;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.test.MiniCluster;
import org.apache.pig.test.Util;
import org.joda.time.DateTime;
import org.junit.Test;
public class TestStreamingUDF {
private static PigServer pigServerLocal = null;
private static PigServer pigServerMapReduce = null;
private TupleFactory tf = TupleFactory.getInstance();
private static MiniCluster cluster = MiniCluster.buildCluster();
@Test
public void testPythonUDF_onCluster() throws Exception {
pigServerMapReduce = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'c:chararray\')",
"def py_func(one,two):",
" return one + two"
};
Util.createLocalInputFile("pyfile_mr.py", pythonScript);
String[] input = {
"field10\tfield11",
"field20\tfield21"
};
Util.createLocalInputFile("input_mr", input);
Util.copyFromLocalToCluster(cluster, "input_mr", "input_mr");
pigServerMapReduce.registerQuery("REGISTER 'pyfile_mr.py' USING streaming_python AS pf;");
pigServerMapReduce.registerQuery("A = LOAD 'input_mr' as (c1:chararray, c2:chararray);");
pigServerMapReduce.registerQuery("B = FOREACH A generate pf.py_func(c1, c2);");
Iterator<Tuple> iter = pigServerMapReduce.openIterator("B");
assertTrue(iter.hasNext());
Tuple actual0 = iter.next();
assertTrue(iter.hasNext());
Tuple actual1 = iter.next();
Tuple expected0 = tf.newTuple("field10field11");
Tuple expected1 = tf.newTuple("field20field21");
assertEquals(expected0, actual0);
assertEquals(expected1, actual1);
}
@Test
public void testPythonUDF() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'c:chararray\')",
"def py_func(one,two):",
" return one + two"
};
Util.createLocalInputFile( "pyfile.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(2);
t0.set(0, "field10");
t0.set(1, "field11");
Tuple t1 = tf.newTuple(2);
t1.set(0, "field20");
t1.set(1, "field21");
data.set("testTuples", "c1:chararray,c2:chararray", t0, t1);
pigServerLocal.registerQuery("REGISTER 'pyfile.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("A = LOAD 'testTuples' USING mock.Storage();");
pigServerLocal.registerQuery("B = FOREACH A generate pf.py_func(c1, c2);");
pigServerLocal.registerQuery("STORE B INTO 'out' USING mock.Storage();");
Tuple expected0 = tf.newTuple("field10field11");
Tuple expected1 = tf.newTuple("field20field21");
List<Tuple> out = data.get("out");
assertEquals(expected0, out.get(0));
assertEquals(expected1, out.get(1));
}
@Test
public void testPythonUDF_withNewline() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'c:chararray\')",
"def py_func(one,two):",
" return '%s\\n%s' % (one,two)"
};
Util.createLocalInputFile( "pyfileNL.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(2);
t0.set(0, "field10");
t0.set(1, "field11");
Tuple t1 = tf.newTuple(2);
t1.set(0, "field20");
t1.set(1, "field21");
data.set("testTuplesNL", "c1:chararray,c2:chararray", t0, t1);
pigServerLocal.registerQuery("REGISTER 'pyfileNL.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("A = LOAD 'testTuplesNL' USING mock.Storage();");
pigServerLocal.registerQuery("B = FOREACH A generate pf.py_func(c1, c2);");
pigServerLocal.registerQuery("STORE B INTO 'outNL' USING mock.Storage();");
Tuple expected0 = tf.newTuple("field10\nfield11");
Tuple expected1 = tf.newTuple("field20\nfield21");
List<Tuple> out = data.get("outNL");
assertEquals(expected0, out.get(0));
assertEquals(expected1, out.get(1));
}
@Test
public void testPythonUDF__withBigInteger() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'biout:biginteger\')",
"def py_func(bi):",
" return bi"
};
Util.createLocalInputFile( "pyfile_bi.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(new BigInteger("123456789012345678901234567890"));
Tuple t1 = tf.newTuple(new BigInteger("9123456789012345678901234567890"));
data.set("testBiTuples", "bi:biginteger", t0, t1);
pigServerLocal.registerQuery("REGISTER 'pyfile_bi.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("A = LOAD 'testBiTuples' USING mock.Storage();");
pigServerLocal.registerQuery("B = FOREACH A generate pf.py_func(bi);");
pigServerLocal.registerQuery("STORE B INTO 'bi_out' USING mock.Storage();");
List<Tuple> out = data.get("bi_out");
assertEquals(t0, out.get(0));
assertEquals(t1, out.get(1));
}
@Test
public void testPythonUDF__withBigDecimal() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'bdout:bigdecimal\')",
"def py_func(bd):",
" return bd"
};
Util.createLocalInputFile( "pyfile_bd.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(new BigDecimal("123456789012345678901234567890.12345"));
Tuple t1 = tf.newTuple(new BigDecimal("9123456789012345678901234567890.12345"));
data.set("testBdTuples", "bd:bigdecimal", t0, t1);
pigServerLocal.registerQuery("REGISTER 'pyfile_bd.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("A = LOAD 'testBdTuples' USING mock.Storage();");
pigServerLocal.registerQuery("B = FOREACH A generate pf.py_func(bd);");
pigServerLocal.registerQuery("STORE B INTO 'bd_out' USING mock.Storage();");
//We lose precision when we go to python.
List<Tuple> out = data.get("bd_out");
Float e0 = ((BigDecimal)t0.get(0)).floatValue();
Float e1 = ((BigDecimal)t1.get(0)).floatValue();
assertEquals(e0, ((BigDecimal) out.get(0).get(0)).floatValue(), 0.1);
assertEquals(e1, ((BigDecimal) out.get(1).get(0)).floatValue(), 0.1);
}
@Test
public void testPythonUDF__withDateTime() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"from pig_util import outputSchema",
"@outputSchema(\'d:datetime\')",
"def py_func(dt):",
" return dt"
};
Util.createLocalInputFile( "pyfile_dt.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(new DateTime());
Tuple t1 = tf.newTuple(new DateTime());
data.set("testDateTuples", "d:datetime", t0, t1);
pigServerLocal.registerQuery("REGISTER 'pyfile_dt.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("A = LOAD 'testDateTuples' USING mock.Storage();");
pigServerLocal.registerQuery("B = FOREACH A generate pf.py_func(d);");
pigServerLocal.registerQuery("STORE B INTO 'date_out' USING mock.Storage();");
List<Tuple> out = data.get("date_out");
assertEquals(t0, out.get(0));
assertEquals(t1, out.get(1));
}
@Test
public void testPythonUDF__allTypes() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"# -*- coding: utf-8 -*-",
"from pig_util import outputSchema",
"import sys",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def get_tuple_output():",
" result = (None, 32, 1000000099990000L, 32.0, 3200.1234678509, 'Some String', 'Hello\\u2026Hello', u'Hello\\u2026Hello', b'Some Byte Array')",
" return result",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def crazy_tuple_identity(ct):",
" print ct",
" return ct",
"",
"@outputSchema('mappy:map[]')",
"def add_map():",
" return {u'Weird\\u2026Name' : u'Weird \\u2026 Value',",
" 'SomeNum' : 32,",
" 'Simple Name' : 'Simple Value' }",
"",
"",
"@outputSchema('silly:chararray')",
"def silly(silly_word):",
" print silly_word.encode('utf-8')",
" return silly_word",
"",
"",
"@outputSchema('final_output:bag{t:tuple(user_id:chararray,age:int,tuple_output:tuple(nully:chararray,inty:int,longy:long,floaty:float,doubly:double,chararrayy:chararray,utf_chararray_basic_string:chararray,utf_chararray_unicode:chararray,bytearrayy:bytearray),mappy:map[],silly:chararray)}')",
"def bag_identity(bag):",
" return bag"
};
Util.createLocalInputFile("allfile.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(2);
t0.set(0, "user1");
t0.set(1, 10);
Tuple t1 = tf.newTuple(2);
t1.set(0, "user2");
t1.set(1, 11);
data.set("userTuples", "user_id:chararray,age:int", t0, t1);
pigServerLocal.registerQuery("REGISTER 'allfile.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("users = LOAD 'userTuples' USING mock.Storage();");
pigServerLocal.registerQuery("crazy_tuple = FOREACH users GENERATE user_id, age, pf.get_tuple_output();");
pigServerLocal.registerQuery("crazy_tuple_fun = FOREACH crazy_tuple GENERATE user_id, age, pf.crazy_tuple_identity(tuple_output);");
pigServerLocal.registerQuery("crazy_tuple_with_map = FOREACH crazy_tuple_fun GENERATE user_id, age, tuple_output, pf.add_map(), pf.silly('\u2026');");
pigServerLocal.registerQuery("crazy_group = GROUP crazy_tuple_with_map BY (age);");
pigServerLocal.registerQuery("out = FOREACH crazy_group GENERATE group, pf.bag_identity(crazy_tuple_with_map);");
pigServerLocal.registerQuery("STORE out INTO 'all_out' USING mock.Storage();");
List<Tuple> out = data.get("all_out");
/*
* Expected output for first tuple.
* (10,
- * {(user1,10,(,32,1000000099990000,32.0,3200.12346785,Some String,Hello\u2026Hello,Hello�Hello,Some Byte Array),
- * [Simple Name#Simple Value,SomeNum#32,Weird�Name#Weird � Value],�)
+ * {(user1,10,(,32,1000000099990000,32.0,3200.12346785,Some String,Hello\u2026Hello,Hello\u2026Hello,Some Byte Array),
+ * [Simple Name#Simple Value,SomeNum#32,Weird\u2026Name#Weird \u2026 Value],\u2026)
* })
*/
//Get Bag
DataBag bag = (DataBag) out.get(0).get(1);
assertEquals(1, bag.size());
//Get First Bag Tuple
Tuple innerTuple = bag.iterator().next();
assertEquals(5, innerTuple.size());
//Check one field in innermost tuple
assertEquals("Hello\\u2026Hello", ((Tuple) innerTuple.get(2)).get(6));
}
}
| true | true | public void testPythonUDF__allTypes() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"# -*- coding: utf-8 -*-",
"from pig_util import outputSchema",
"import sys",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def get_tuple_output():",
" result = (None, 32, 1000000099990000L, 32.0, 3200.1234678509, 'Some String', 'Hello\\u2026Hello', u'Hello\\u2026Hello', b'Some Byte Array')",
" return result",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def crazy_tuple_identity(ct):",
" print ct",
" return ct",
"",
"@outputSchema('mappy:map[]')",
"def add_map():",
" return {u'Weird\\u2026Name' : u'Weird \\u2026 Value',",
" 'SomeNum' : 32,",
" 'Simple Name' : 'Simple Value' }",
"",
"",
"@outputSchema('silly:chararray')",
"def silly(silly_word):",
" print silly_word.encode('utf-8')",
" return silly_word",
"",
"",
"@outputSchema('final_output:bag{t:tuple(user_id:chararray,age:int,tuple_output:tuple(nully:chararray,inty:int,longy:long,floaty:float,doubly:double,chararrayy:chararray,utf_chararray_basic_string:chararray,utf_chararray_unicode:chararray,bytearrayy:bytearray),mappy:map[],silly:chararray)}')",
"def bag_identity(bag):",
" return bag"
};
Util.createLocalInputFile("allfile.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(2);
t0.set(0, "user1");
t0.set(1, 10);
Tuple t1 = tf.newTuple(2);
t1.set(0, "user2");
t1.set(1, 11);
data.set("userTuples", "user_id:chararray,age:int", t0, t1);
pigServerLocal.registerQuery("REGISTER 'allfile.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("users = LOAD 'userTuples' USING mock.Storage();");
pigServerLocal.registerQuery("crazy_tuple = FOREACH users GENERATE user_id, age, pf.get_tuple_output();");
pigServerLocal.registerQuery("crazy_tuple_fun = FOREACH crazy_tuple GENERATE user_id, age, pf.crazy_tuple_identity(tuple_output);");
pigServerLocal.registerQuery("crazy_tuple_with_map = FOREACH crazy_tuple_fun GENERATE user_id, age, tuple_output, pf.add_map(), pf.silly('\u2026');");
pigServerLocal.registerQuery("crazy_group = GROUP crazy_tuple_with_map BY (age);");
pigServerLocal.registerQuery("out = FOREACH crazy_group GENERATE group, pf.bag_identity(crazy_tuple_with_map);");
pigServerLocal.registerQuery("STORE out INTO 'all_out' USING mock.Storage();");
List<Tuple> out = data.get("all_out");
/*
* Expected output for first tuple.
* (10,
* {(user1,10,(,32,1000000099990000,32.0,3200.12346785,Some String,Hello\u2026Hello,Hello�Hello,Some Byte Array),
* [Simple Name#Simple Value,SomeNum#32,Weird�Name#Weird � Value],�)
* })
*/
//Get Bag
DataBag bag = (DataBag) out.get(0).get(1);
assertEquals(1, bag.size());
//Get First Bag Tuple
Tuple innerTuple = bag.iterator().next();
assertEquals(5, innerTuple.size());
//Check one field in innermost tuple
assertEquals("Hello\\u2026Hello", ((Tuple) innerTuple.get(2)).get(6));
}
| public void testPythonUDF__allTypes() throws Exception {
pigServerLocal = new PigServer(ExecType.LOCAL);
String[] pythonScript = {
"# -*- coding: utf-8 -*-",
"from pig_util import outputSchema",
"import sys",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def get_tuple_output():",
" result = (None, 32, 1000000099990000L, 32.0, 3200.1234678509, 'Some String', 'Hello\\u2026Hello', u'Hello\\u2026Hello', b'Some Byte Array')",
" return result",
"",
"@outputSchema('tuple_output:tuple(nully:chararray, inty:int, longy:long, floaty:float, doubly:double, chararrayy:chararray, utf_chararray_basic_string:chararray, utf_chararray_unicode:chararray, bytearrayy:bytearray)')",
"def crazy_tuple_identity(ct):",
" print ct",
" return ct",
"",
"@outputSchema('mappy:map[]')",
"def add_map():",
" return {u'Weird\\u2026Name' : u'Weird \\u2026 Value',",
" 'SomeNum' : 32,",
" 'Simple Name' : 'Simple Value' }",
"",
"",
"@outputSchema('silly:chararray')",
"def silly(silly_word):",
" print silly_word.encode('utf-8')",
" return silly_word",
"",
"",
"@outputSchema('final_output:bag{t:tuple(user_id:chararray,age:int,tuple_output:tuple(nully:chararray,inty:int,longy:long,floaty:float,doubly:double,chararrayy:chararray,utf_chararray_basic_string:chararray,utf_chararray_unicode:chararray,bytearrayy:bytearray),mappy:map[],silly:chararray)}')",
"def bag_identity(bag):",
" return bag"
};
Util.createLocalInputFile("allfile.py", pythonScript);
Data data = resetData(pigServerLocal);
Tuple t0 = tf.newTuple(2);
t0.set(0, "user1");
t0.set(1, 10);
Tuple t1 = tf.newTuple(2);
t1.set(0, "user2");
t1.set(1, 11);
data.set("userTuples", "user_id:chararray,age:int", t0, t1);
pigServerLocal.registerQuery("REGISTER 'allfile.py' USING streaming_python AS pf;");
pigServerLocal.registerQuery("users = LOAD 'userTuples' USING mock.Storage();");
pigServerLocal.registerQuery("crazy_tuple = FOREACH users GENERATE user_id, age, pf.get_tuple_output();");
pigServerLocal.registerQuery("crazy_tuple_fun = FOREACH crazy_tuple GENERATE user_id, age, pf.crazy_tuple_identity(tuple_output);");
pigServerLocal.registerQuery("crazy_tuple_with_map = FOREACH crazy_tuple_fun GENERATE user_id, age, tuple_output, pf.add_map(), pf.silly('\u2026');");
pigServerLocal.registerQuery("crazy_group = GROUP crazy_tuple_with_map BY (age);");
pigServerLocal.registerQuery("out = FOREACH crazy_group GENERATE group, pf.bag_identity(crazy_tuple_with_map);");
pigServerLocal.registerQuery("STORE out INTO 'all_out' USING mock.Storage();");
List<Tuple> out = data.get("all_out");
/*
* Expected output for first tuple.
* (10,
* {(user1,10,(,32,1000000099990000,32.0,3200.12346785,Some String,Hello\u2026Hello,Hello\u2026Hello,Some Byte Array),
* [Simple Name#Simple Value,SomeNum#32,Weird\u2026Name#Weird \u2026 Value],\u2026)
* })
*/
//Get Bag
DataBag bag = (DataBag) out.get(0).get(1);
assertEquals(1, bag.size());
//Get First Bag Tuple
Tuple innerTuple = bag.iterator().next();
assertEquals(5, innerTuple.size());
//Check one field in innermost tuple
assertEquals("Hello\\u2026Hello", ((Tuple) innerTuple.get(2)).get(6));
}
|
diff --git a/src/test/org/apache/hadoop/mapred/TestMapredHeartbeat.java b/src/test/org/apache/hadoop/mapred/TestMapredHeartbeat.java
index 069732028..04e9b898c 100644
--- a/src/test/org/apache/hadoop/mapred/TestMapredHeartbeat.java
+++ b/src/test/org/apache/hadoop/mapred/TestMapredHeartbeat.java
@@ -1,107 +1,108 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapred.JobConf;
public class TestMapredHeartbeat extends TestCase {
public void testJobDirCleanup() throws IOException {
MiniMRCluster mr = null;
try {
// test the default heartbeat interval
int taskTrackers = 2;
JobConf conf = new JobConf();
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
JobClient jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval
taskTrackers = 5;
conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND, 1);
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(taskTrackers * 1000,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval is capped with min value
taskTrackers = 5;
- conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND, 10);
+ conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND,
+ (int)Math.ceil((taskTrackers * 1000.0) / MRConstants.HEARTBEAT_INTERVAL_MIN) );
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
} finally {
if (mr != null) { mr.shutdown(); }
}
}
public void testOutOfBandHeartbeats() throws Exception {
MiniDFSCluster dfs = null;
MiniMRCluster mr = null;
try {
Configuration conf = new Configuration();
dfs = new MiniDFSCluster(conf, 4, true, null);
int taskTrackers = 1;
JobConf jobConf = new JobConf();
jobConf.setFloat(JobTracker.JT_HEARTBEATS_SCALING_FACTOR, 30.0f);
jobConf.setBoolean(TaskTracker.TT_OUTOFBAND_HEARBEAT, true);
mr = new MiniMRCluster(taskTrackers,
dfs.getFileSystem().getUri().toString(), 3,
null, null, jobConf);
long start = System.currentTimeMillis();
TestMiniMRDFSSort.runRandomWriter(mr.createJobConf(), new Path("rw"));
long end = System.currentTimeMillis();
final int expectedRuntimeSecs = 120;
final int runTimeSecs = (int)((end-start) / 1000);
System.err.println("Runtime is " + runTimeSecs);
assertEquals("Actual runtime " + runTimeSecs + "s not less than expected " +
"runtime of " + expectedRuntimeSecs + "s!",
true, (runTimeSecs <= 120));
} finally {
if (mr != null) { mr.shutdown(); }
if (dfs != null) { dfs.shutdown(); }
}
}
}
| true | true | public void testJobDirCleanup() throws IOException {
MiniMRCluster mr = null;
try {
// test the default heartbeat interval
int taskTrackers = 2;
JobConf conf = new JobConf();
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
JobClient jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval
taskTrackers = 5;
conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND, 1);
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(taskTrackers * 1000,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval is capped with min value
taskTrackers = 5;
conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND, 10);
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
} finally {
if (mr != null) { mr.shutdown(); }
}
}
| public void testJobDirCleanup() throws IOException {
MiniMRCluster mr = null;
try {
// test the default heartbeat interval
int taskTrackers = 2;
JobConf conf = new JobConf();
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
JobClient jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval
taskTrackers = 5;
conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND, 1);
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(taskTrackers * 1000,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
mr.shutdown();
// test configured heartbeat interval is capped with min value
taskTrackers = 5;
conf.setInt(JobTracker.JT_HEARTBEATS_IN_SECOND,
(int)Math.ceil((taskTrackers * 1000.0) / MRConstants.HEARTBEAT_INTERVAL_MIN) );
mr = new MiniMRCluster(taskTrackers, "file:///", 3,
null, null, conf);
jc = new JobClient(mr.createJobConf());
while(jc.getClusterStatus().getTaskTrackers() != taskTrackers) {
UtilsForTests.waitFor(100);
}
assertEquals(MRConstants.HEARTBEAT_INTERVAL_MIN,
mr.getJobTrackerRunner().getJobTracker().getNextHeartbeatInterval());
} finally {
if (mr != null) { mr.shutdown(); }
}
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/accesscontrol/AccessModeResource.java b/src/main/java/pl/psnc/dl/wf4ever/accesscontrol/AccessModeResource.java
index bcd6cba9..976658e3 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/accesscontrol/AccessModeResource.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/accesscontrol/AccessModeResource.java
@@ -1,122 +1,122 @@
package pl.psnc.dl.wf4ever.accesscontrol;
import java.net.URI;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import pl.psnc.dl.wf4ever.accesscontrol.dicts.Mode;
import pl.psnc.dl.wf4ever.accesscontrol.dicts.Role;
import pl.psnc.dl.wf4ever.accesscontrol.model.AccessMode;
import pl.psnc.dl.wf4ever.accesscontrol.model.Permission;
import pl.psnc.dl.wf4ever.accesscontrol.model.dao.ModeDAO;
import pl.psnc.dl.wf4ever.accesscontrol.model.dao.PermissionDAO;
import pl.psnc.dl.wf4ever.auth.RequestAttribute;
import pl.psnc.dl.wf4ever.db.dao.UserProfileDAO;
import pl.psnc.dl.wf4ever.exceptions.BadRequestException;
import pl.psnc.dl.wf4ever.model.Builder;
import pl.psnc.dl.wf4ever.model.RO.ResearchObject;
/**
* API for setting Research Object access mode.
*
* @author pejot
*
*/
@Path("accesscontrol/modes/")
public class AccessModeResource {
/** logger. */
private static final Logger LOGGER = Logger.getLogger(AccessModeResource.class);
/** URI info. */
@Context
UriInfo uriInfo;
/** Resource builder. */
@RequestAttribute("Builder")
private Builder builder;
/** Access Mode dao. */
private ModeDAO dao = new ModeDAO();
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response setMode(AccessMode mode)
throws BadRequestException {
//first check permissions
PermissionDAO permissionDAO = new PermissionDAO();
UserProfileDAO userDAO = new UserProfileDAO();
//perhaps he is an admin.
//admin can everything
if (!builder.getUser().getRole().equals(pl.psnc.dl.wf4ever.dl.UserMetadata.Role.ADMIN)) {
List<Permission> permissions = permissionDAO.findByUserROAndPermission(
userDAO.findByLogin(builder.getUser().getLogin()), mode.getRo(), Role.OWNER);
if (permissions.size() == 0) {
throw new BadRequestException("The given ro doesn't exists or doesn't belong to user");
} else if (permissions.size() > 1) {
LOGGER.error("Multiply RO authors detected for" + mode.getRo());
throw new WebApplicationException(500);
}
}
AccessMode storedMode = dao.findByResearchObject(mode.getRo());
if (storedMode == null) {
LOGGER.error("Mode for " + mode.getRo() + " Couldn't be found");
storedMode = new AccessMode();
storedMode.setRo(mode.getRo());
}
//detect change
if(mode.getMode() == Mode.PRIVATE && (storedMode.getMode() == Mode.PUBLIC || storedMode.getMode() == Mode.OPEN)) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.updateIndexAttributes();
}
- if((storedMode.getMode() == Mode.PUBLIC || storedMode.getMode() == Mode.OPEN) && mode.getMode() == Mode.PRIVATE) {
+ if((mode.getMode() == Mode.PUBLIC || mode.getMode() == Mode.OPEN) && storedMode.getMode() == Mode.PRIVATE) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.deleteIndexAttributes();
}
storedMode.setMode(mode.getMode());
dao.save(storedMode);
//if storedmode == 0
storedMode.setUri(uriInfo.getRequestUri().resolve(storedMode.getId().toString()));
return Response.created(uriInfo.getRequestUri().resolve(storedMode.getId().toString())).entity(storedMode)
.build();
}
@GET
@Path("{mode_id}/")
public AccessMode getModeById(@PathParam("mode_id") String mode_id) {
AccessMode result = dao.findById(Integer.valueOf(mode_id));
if (result != null) {
result.setUri(uriInfo.getRequestUri().resolve(result.getId().toString()));
}
return result;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public AccessMode getModeByRo(@QueryParam("ro") String ro) {
AccessMode result = dao.findByResearchObject(ro);
if (result != null) {
result.setUri(uriInfo.getBaseUri().resolve("accesscontrol/modes/").resolve(result.getId().toString()));
}
return result;
}
}
| true | true | public Response setMode(AccessMode mode)
throws BadRequestException {
//first check permissions
PermissionDAO permissionDAO = new PermissionDAO();
UserProfileDAO userDAO = new UserProfileDAO();
//perhaps he is an admin.
//admin can everything
if (!builder.getUser().getRole().equals(pl.psnc.dl.wf4ever.dl.UserMetadata.Role.ADMIN)) {
List<Permission> permissions = permissionDAO.findByUserROAndPermission(
userDAO.findByLogin(builder.getUser().getLogin()), mode.getRo(), Role.OWNER);
if (permissions.size() == 0) {
throw new BadRequestException("The given ro doesn't exists or doesn't belong to user");
} else if (permissions.size() > 1) {
LOGGER.error("Multiply RO authors detected for" + mode.getRo());
throw new WebApplicationException(500);
}
}
AccessMode storedMode = dao.findByResearchObject(mode.getRo());
if (storedMode == null) {
LOGGER.error("Mode for " + mode.getRo() + " Couldn't be found");
storedMode = new AccessMode();
storedMode.setRo(mode.getRo());
}
//detect change
if(mode.getMode() == Mode.PRIVATE && (storedMode.getMode() == Mode.PUBLIC || storedMode.getMode() == Mode.OPEN)) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.updateIndexAttributes();
}
if((storedMode.getMode() == Mode.PUBLIC || storedMode.getMode() == Mode.OPEN) && mode.getMode() == Mode.PRIVATE) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.deleteIndexAttributes();
}
storedMode.setMode(mode.getMode());
dao.save(storedMode);
//if storedmode == 0
storedMode.setUri(uriInfo.getRequestUri().resolve(storedMode.getId().toString()));
return Response.created(uriInfo.getRequestUri().resolve(storedMode.getId().toString())).entity(storedMode)
.build();
}
| public Response setMode(AccessMode mode)
throws BadRequestException {
//first check permissions
PermissionDAO permissionDAO = new PermissionDAO();
UserProfileDAO userDAO = new UserProfileDAO();
//perhaps he is an admin.
//admin can everything
if (!builder.getUser().getRole().equals(pl.psnc.dl.wf4ever.dl.UserMetadata.Role.ADMIN)) {
List<Permission> permissions = permissionDAO.findByUserROAndPermission(
userDAO.findByLogin(builder.getUser().getLogin()), mode.getRo(), Role.OWNER);
if (permissions.size() == 0) {
throw new BadRequestException("The given ro doesn't exists or doesn't belong to user");
} else if (permissions.size() > 1) {
LOGGER.error("Multiply RO authors detected for" + mode.getRo());
throw new WebApplicationException(500);
}
}
AccessMode storedMode = dao.findByResearchObject(mode.getRo());
if (storedMode == null) {
LOGGER.error("Mode for " + mode.getRo() + " Couldn't be found");
storedMode = new AccessMode();
storedMode.setRo(mode.getRo());
}
//detect change
if(mode.getMode() == Mode.PRIVATE && (storedMode.getMode() == Mode.PUBLIC || storedMode.getMode() == Mode.OPEN)) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.updateIndexAttributes();
}
if((mode.getMode() == Mode.PUBLIC || mode.getMode() == Mode.OPEN) && storedMode.getMode() == Mode.PRIVATE) {
ResearchObject researchObject = ResearchObject.get(builder, URI.create(mode.getRo()));
researchObject.deleteIndexAttributes();
}
storedMode.setMode(mode.getMode());
dao.save(storedMode);
//if storedmode == 0
storedMode.setUri(uriInfo.getRequestUri().resolve(storedMode.getId().toString()));
return Response.created(uriInfo.getRequestUri().resolve(storedMode.getId().toString())).entity(storedMode)
.build();
}
|
diff --git a/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java b/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java
index c9b5e6b..6094de7 100644
--- a/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java
+++ b/src/minecraft/java/org/darkstorm/darkbot/minecraftbot/ai/FarmingTask.java
@@ -1,782 +1,783 @@
package org.darkstorm.darkbot.minecraftbot.ai;
import java.util.*;
import org.darkstorm.darkbot.minecraftbot.MinecraftBot;
import org.darkstorm.darkbot.minecraftbot.events.*;
import org.darkstorm.darkbot.minecraftbot.events.EventListener;
import org.darkstorm.darkbot.minecraftbot.events.world.BlockChangeEvent;
import org.darkstorm.darkbot.minecraftbot.protocol.ConnectionHandler;
import org.darkstorm.darkbot.minecraftbot.protocol.bidirectional.*;
import org.darkstorm.darkbot.minecraftbot.protocol.bidirectional.Packet18Animation.Animation;
import org.darkstorm.darkbot.minecraftbot.protocol.writeable.*;
import org.darkstorm.darkbot.minecraftbot.world.World;
import org.darkstorm.darkbot.minecraftbot.world.block.*;
import org.darkstorm.darkbot.minecraftbot.world.entity.*;
import org.darkstorm.darkbot.minecraftbot.world.item.*;
public class FarmingTask implements Task, EventListener {
public enum StorageAction {
STORE,
SELL
}
private static final boolean[] UNPLACEABLE = new boolean[256];
private static final int[] HOES;
private static final int[] FARMED_ITEMS;
static {
UNPLACEABLE[0] = true;
UNPLACEABLE[8] = true;
UNPLACEABLE[9] = true;
UNPLACEABLE[10] = true;
UNPLACEABLE[11] = true;
UNPLACEABLE[26] = true;
UNPLACEABLE[31] = true;
UNPLACEABLE[51] = true;
UNPLACEABLE[54] = true;
UNPLACEABLE[61] = true;
UNPLACEABLE[62] = true;
UNPLACEABLE[64] = true;
UNPLACEABLE[69] = true;
UNPLACEABLE[71] = true;
UNPLACEABLE[77] = true;
UNPLACEABLE[78] = true;
UNPLACEABLE[96] = true;
UNPLACEABLE[107] = true;
HOES = new int[] { 290, 291, 292, 293, 294 };
FARMED_ITEMS = new int[] { 372, 295, 296, 338, 361, 362, 86, 360 };
}
private final MinecraftBot bot;
private boolean running = false;
private BlockLocation currentlyBreaking;
private int ticksSinceBreak, ticksWait, itemCheckWait;
private BlockLocation currentChest;
private List<BlockLocation> fullChests = new ArrayList<BlockLocation>();
private BlockArea region;
private StorageAction storageAction = StorageAction.STORE;
private boolean selling;
public FarmingTask(final MinecraftBot bot) {
this.bot = bot;
bot.getEventManager().registerListener(this);
}
@Override
public synchronized boolean isPreconditionMet() {
return running;
}
@Override
public synchronized boolean start(String... options) {
if(options.length > 0) {
BlockLocation endpoint1 = new BlockLocation(Integer.parseInt(options[0]), Integer.parseInt(options[1]), Integer.parseInt(options[2]));
BlockLocation endpoint2 = new BlockLocation(Integer.parseInt(options[3]), Integer.parseInt(options[4]), Integer.parseInt(options[5]));
region = new BlockArea(endpoint1, endpoint2);
} else
region = null;
running = true;
return true;
}
@Override
public synchronized void stop() {
running = false;
}
@Override
public synchronized void run() {
if(currentlyBreaking != null) {
ticksSinceBreak++;
if(ticksSinceBreak > 200)
currentlyBreaking = null;
return;
}
ticksSinceBreak = 0;
TaskManager taskManager = bot.getTaskManager();
EatTask eatTask = taskManager.getTaskFor(EatTask.class);
if(eatTask.isActive())
return;
if(ticksWait > 0) {
ticksWait--;
return;
}
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return;
BlockLocation ourLocation = new BlockLocation(player.getLocation());
PlayerInventory inventory = player.getInventory();
boolean store = !inventory.contains(0);
if(!store && storageAction.equals(StorageAction.SELL) && selling)
for(int id : FARMED_ITEMS)
if(inventory.getCount(id) >= 64)
store = true;
if(store) {
System.out.println("Inventory is full!!!");
if(storageAction.equals(StorageAction.STORE)) {
if(player.getWindow() instanceof ChestInventory) {
System.out.println("Chest is open!!!");
ChestInventory chest = (ChestInventory) player.getWindow();
int freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1) {
if(currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
System.out.println("Closed chest, no spaces!!!");
ticksWait = 16;
return;
}
for(int i = 0; i < 36; i++) {
ItemStack item = chest.getItemAt(chest.getSize() + i);
if(item == null)
continue;
boolean found = false;
for(int id : FARMED_ITEMS)
if(id == item.getId())
found = true;
if(!found)
continue;
chest.selectItemAt(chest.getSize() + i);
int index = -1;
for(int j = 0; j < chest.getSize(); j++) {
if(chest.getItemAt(j) == null) {
index = j;
break;
}
}
if(index == -1)
continue;
chest.selectItemAt(index);
}
freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1 && currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
currentChest = null;
System.out.println("Closed chest!!!");
ticksWait = 16;
return;
} else {
BlockLocation[] chests = getBlocks(54, 32);
chestLoop: for(BlockLocation chest : chests) {
if(!fullChests.contains(chest) && !isChestCovered(chest)) {
BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > chest.getY())
face = 1;
else if(walk.getX() > chest.getX())
face = 5;
else if(walk.getX() < chest.getX())
face = 4;
else if(walk.getZ() > chest.getZ())
face = 3;
else if(walk.getZ() < chest.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue chestLoop;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue chestLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
if(!ourLocation.equals(closestWalk)) {
System.out.println("Walking to chest!!!");
bot.setActivity(new WalkActivity(bot, closestWalk));
return;
}
System.out.println("Opening chest!!!");
placeAt(originalWalk, face);
currentChest = chest;
ticksWait = 80;
return;
}
}
}
} else if(storageAction.equals(StorageAction.SELL)) {
if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) {
bot.say("/spawn");
ticksWait = 200;
return;
}
selling = true;
BlockLocation[] signs = getBlocks(68, 32);
signLoop: for(BlockLocation sign : signs) {
TileEntity tile = world.getTileEntityAt(sign);
if(tile == null || !(tile instanceof SignTileEntity))
continue;
SignTileEntity signTile = (SignTileEntity) tile;
String[] text = signTile.getText();
boolean found = false;
if(text[0].contains("[Sell]"))
for(int id : FARMED_ITEMS)
- if(text[2].equals(Integer.toString(id)) && inventory.contains(id))
+ if(text[2].equals(Integer.toString(id)) && inventory.getCount(id) >= 64)
found = true;
if(!found)
continue;
if(player.getDistanceTo(sign) > 3) {
BlockLocation closestWalk = sign;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue signLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
player.walkTo(closestWalk);
System.out.println("Walking to sign @ " + sign);
return;
}
BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > sign.getY())
face = 1;
else if(walk.getX() > sign.getX())
face = 5;
else if(walk.getX() < sign.getX())
face = 4;
else if(walk.getZ() > sign.getZ())
face = 3;
else if(walk.getZ() < sign.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue;
placeOn(sign, face);
ticksWait = 4;
return;
}
+ return;
}
}
BlockLocation closest = getClosestFarmable(32);
if(region != null ? !region.contains(ourLocation) : closest == null) {
bot.say("/home");
ticksWait = 200;
return;
}
if(closest == null) {
if(itemCheckWait > 0) {
itemCheckWait--;
return;
}
if(!inventory.contains(0)) {
itemCheckWait = 10;
return;
}
ItemEntity item = getClosestGroundItem(FARMED_ITEMS);
if(item != null) {
System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation());
bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation())));
} else
itemCheckWait = 10;
return;
}
itemCheckWait = 0;
System.out.println("Farming at " + closest + "!");
int id = world.getBlockIdAt(closest);
if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) {
System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest));
BlockLocation walkTo = closest;
if(id == 83)
walkTo = closest.offset(0, -1, 0);
else if(id == 86 || id == 103) {
BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid())
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
}
}
if(closestWalk == null)
return;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
return;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
walkTo = closestWalk;
}
if(!ourLocation.equals(walkTo)) {
bot.setActivity(new WalkActivity(bot, walkTo));
return;
}
breakBlock(closest);
} else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) {
if(id == 104 || id == 105) {
BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) };
for(BlockLocation dirtLocation : locations)
if(world.getBlockIdAt(dirtLocation) == 3)
closest = dirtLocation;
}
int[] tools;
if(id == 88)
tools = new int[] { 372 };
else if(id == 60)
tools = new int[] { 295 };
else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES))
tools = HOES;
// else if(inventory.contains(338) && (id == 3 || id == 12))
// tools = new int[] { 338 };
else
return;
if(!switchTo(tools))
return;
BlockLocation offset = closest.offset(0, 1, 0);
if(!ourLocation.equals(offset)) {
bot.setActivity(new WalkActivity(bot, offset));
return;
}
placeAt(offset);
ticksWait = 5;
}
}
private ItemEntity getClosestGroundItem(int... ids) {
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return null;
Entity[] entities = world.getEntities();
ItemEntity closest = null;
int closestDistance = Integer.MAX_VALUE;
for(Entity entity : entities) {
if(entity instanceof ItemEntity) {
ItemEntity item = (ItemEntity) entity;
if(item.getItem() == null)
continue;
int itemId = item.getItem().getId();
for(int id : ids) {
if(itemId == id) {
int distance = player.getDistanceToSquared(item);
if(distance < closestDistance) {
int blockId = world.getBlockIdAt(new BlockLocation(item.getLocation()));
if(!BlockType.getById(blockId).isSolid()) {
closest = item;
closestDistance = distance;
}
}
}
}
}
}
return closest;
}
private boolean isChestCovered(BlockLocation chest) {
if(checkChest(chest))
return true;
BlockLocation[] surrounding = new BlockLocation[] { chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) };
for(BlockLocation otherChest : surrounding)
if(bot.getWorld().getBlockIdAt(otherChest) == 54 && checkChest(otherChest))
return true;
return false;
}
private boolean checkChest(BlockLocation chest) {
int idAbove = bot.getWorld().getBlockIdAt(chest.offset(0, 1, 0));
if(!BlockType.getById(idAbove).isSolid())
return false;
BlockType[] noncovers = new BlockType[] { BlockType.CHEST, BlockType.ENDER_CHEST, BlockType.STEP, BlockType.BED_BLOCK, BlockType.ANVIL, BlockType.BREWING_STAND, BlockType.WOOD_STEP, BlockType.WOOD_STAIRS, BlockType.BRICK_STAIRS, BlockType.COBBLESTONE_STAIRS, BlockType.NETHER_BRICK_STAIRS, BlockType.SANDSTONE_STAIRS, BlockType.SMOOTH_STAIRS };
for(BlockType type : noncovers)
if(idAbove == type.getId())
return false;
return true;
}
@Override
public synchronized boolean isActive() {
return running;
}
@EventHandler
public synchronized void onBlockChange(BlockChangeEvent event) {
BlockLocation location = event.getLocation();
Block newBlock = event.getNewBlock();
if((event.getOldBlock() == null && newBlock == null) || (event.getOldBlock() != null && newBlock != null && event.getOldBlock().getId() == newBlock.getId()))
return;
if(newBlock == null || newBlock.getId() == 0) {
if(currentlyBreaking != null && currentlyBreaking.equals(location)) {
currentlyBreaking = null;
}
}
}
private BlockLocation getClosestFarmable(int radius) {
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return null;
PlayerInventory inventory = player.getInventory();
boolean hasNetherwarts = inventory.contains(372), hasSeeds = inventory.contains(295), hasHoe = inventory.contains(HOES);
// boolean hasReeds = inventory.contains(338);
BlockLocation ourLocation = new BlockLocation(player.getLocation());
List<BlockLocation> closest = new ArrayList<>();
int closestDistance = Integer.MAX_VALUE, actualFarmType = 0;
for(int x = region != null ? region.getX() - ourLocation.getX() : -radius; x < (region != null ? region.getX() + region.getWidth() - ourLocation.getX() : radius); x++) {
for(int y = region != null ? region.getY() - ourLocation.getY() : -radius / 2; y < (region != null ? region.getY() + region.getHeight() - ourLocation.getY() : radius / 2); y++) {
for(int z = region != null ? region.getZ() - ourLocation.getZ() : -radius; z < (region != null ? region.getZ() + region.getLength() - ourLocation.getZ() : radius); z++) {
BlockLocation location = new BlockLocation(ourLocation.getX() + x, ourLocation.getY() + y, ourLocation.getZ() + z);
int distance = ourLocation.getDistanceToSquared(location);
if(distance <= closestDistance) {
// System.out.println("[" + x + "," + y + "," + z + "] "
// + distance + " -> " + closestDistance);
int id = world.getBlockIdAt(location);
int idAbove = world.getBlockIdAt(location.offset(0, 1, 0));
int idBelow = world.getBlockIdAt(location.offset(0, -1, 0));
int metadata = world.getBlockMetadataAt(location);
boolean pumpkinWatermelonDirt = false;
boolean plantSeeds = true;
int farmType = actualFarmType;
if(farmType <= 3 && (id == 104 || id == 105) && hasHoe) {
BlockLocation[] locations = new BlockLocation[] { location.offset(-1, -1, 0), location.offset(1, -1, 0), location.offset(0, -1, -1), location.offset(0, -1, 1) };
for(BlockLocation dirtLocation : locations)
if(world.getBlockIdAt(dirtLocation) == 3 && world.getBlockIdAt(dirtLocation.offset(0, 1, 0)) == 0)
pumpkinWatermelonDirt = true;
}
if(farmType <= 1 && (id == 3 && idAbove == 0 && hasHoe && hasSeeds)) {
BlockLocation[] locations = new BlockLocation[] { location.offset(-1, 0, 0), location.offset(1, 0, 0), location.offset(0, 0, -1), location.offset(0, 0, 1) };
for(BlockLocation adjacent : locations) {
int adjacentId = world.getBlockIdAt(adjacent);
if(adjacentId == 104 || adjacentId == 105)
plantSeeds = false;
}
}
if(farmType <= 3 && (pumpkinWatermelonDirt || id == 103 || id == 86 || (id == 115 && metadata > 2) || (id == 59 && metadata > 6) || (id == 83 && idBelow == 83 && idAbove == 83))) {
farmType = 3;
} else if(farmType <= 2 && ((id == 88 && idAbove == 0 && hasNetherwarts) || (id == 60 && idAbove == 0 && hasSeeds)))
farmType = 2;
// else if(farmType < 2
// && ((id == 3 || id == 12) && idAbove == 0 &&
// hasReeds))
// farmType = 2;
else if(farmType <= 1 && (id == 3 && idAbove == 0 && hasHoe && hasSeeds && plantSeeds))
farmType = 1;
else
continue;
if(distance == closestDistance) {
if(farmType != actualFarmType)
continue;
} else
closest.clear();
closest.add(location);
actualFarmType = farmType;
closestDistance = distance;
}
}
}
}
BlockLocation closestLocation = null;
if(closest.size() > 0)
closestLocation = closest.get((int) (Math.random() * closest.size()));
return closestLocation;
}
@SuppressWarnings("unused")
private BlockLocation getClosestBlock(int id, int radius) {
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return null;
BlockLocation ourLocation = new BlockLocation((int) (Math.round(player.getX() - 0.5)), (int) player.getY(), (int) (Math.round(player.getZ() - 0.5)));
BlockLocation closest = null;
int closestDistance = Integer.MAX_VALUE;
for(BlockLocation location : getBlocks(id, radius)) {
int distance = ourLocation.getDistanceToSquared(location);
if(distance < closestDistance) {
closest = location;
closestDistance = distance;
}
}
return closest;
}
private BlockLocation[] getBlocks(int id, int radius) {
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return new BlockLocation[0];
BlockLocation ourLocation = new BlockLocation(player.getLocation());
List<BlockLocation> blocks = new ArrayList<BlockLocation>();
for(int x = region != null ? region.getX() - ourLocation.getX() : -radius; x < (region != null ? region.getX() + region.getWidth() - ourLocation.getX() : radius); x++) {
for(int y = region != null ? region.getY() - ourLocation.getY() : -radius / 2; y < (region != null ? region.getY() + region.getHeight() - ourLocation.getY() : radius / 2); y++) {
for(int z = region != null ? region.getZ() - ourLocation.getZ() : -radius; z < (region != null ? region.getZ() + region.getLength() - ourLocation.getZ() : radius); z++) {
BlockLocation location = new BlockLocation(ourLocation.getX() + x, ourLocation.getY() + y, ourLocation.getZ() + z);
if(world.getBlockIdAt(location) == id)
blocks.add(location);
}
}
}
return blocks.toArray(new BlockLocation[blocks.size()]);
}
private boolean switchTo(int... toolIds) {
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return false;
PlayerInventory inventory = player.getInventory();
int slot = -1;
label: for(int i = 0; i < 36; i++) {
ItemStack item = inventory.getItemAt(i);
if(item == null)
continue;
int id = item.getId();
for(int toolId : toolIds) {
if(id == toolId) {
slot = i;
break label;
}
}
}
if(slot == -1)
return false;
if(inventory.getCurrentHeldSlot() != slot) {
if(slot > 8) {
int hotbarSpace = 9;
for(int hotbarIndex = 0; hotbarIndex < 9; hotbarIndex++) {
if(inventory.getItemAt(hotbarIndex) == null) {
hotbarSpace = hotbarIndex;
break;
} else if(hotbarIndex < hotbarSpace)
hotbarSpace = hotbarIndex;
}
if(hotbarSpace == 9)
return false;
inventory.selectItemAt(slot);
inventory.selectItemAt(hotbarSpace);
if(inventory.getSelectedItem() != null)
inventory.selectItemAt(slot);
inventory.close();
slot = hotbarSpace;
}
inventory.setCurrentHeldSlot(slot);
}
return true;
}
private void breakBlock(BlockLocation location) {
int x = location.getX(), y = location.getY(), z = location.getZ();
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return;
player.face(x, y, z);
ConnectionHandler connectionHandler = bot.getConnectionHandler();
connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true));
connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM));
connectionHandler.sendPacket(new Packet14BlockDig(0, x, y, z, 0));
connectionHandler.sendPacket(new Packet14BlockDig(2, x, y, z, 0));
currentlyBreaking = location;
}
private boolean placeBlockAt(BlockLocation location) {
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return false;
PlayerInventory inventory = player.getInventory();
int slot = -1;
for(int i = 0; i < 36; i++) {
ItemStack item = inventory.getItemAt(i);
if(item == null)
continue;
int id = item.getId();
if(id == 1 || id == 3 || id == 4) {
slot = i;
break;
}
}
if(slot == -1)
return false;
if(!player.switchHeldItems(slot))
return false;
if(player.placeBlock(location))
return true;
return false;
}
private void placeAt(BlockLocation location) {
placeAt(location, getPlacementBlockFaceAt(location));
}
private void placeAt(BlockLocation location, int face) {
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return;
PlayerInventory inventory = player.getInventory();
int originalX = location.getX(), originalY = location.getY(), originalZ = location.getZ();
location = getOffsetBlock(location, face);
if(location == null)
return;
int x = location.getX(), y = location.getY(), z = location.getZ();
player.face(x + ((originalX - x) / 2.0D) + 0.5, y + ((originalY - y) / 2.0D), z + ((originalZ - z) / 2.0D) + 0.5);
ConnectionHandler connectionHandler = bot.getConnectionHandler();
connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true));
connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM));
Packet15Place placePacket = new Packet15Place();
placePacket.xPosition = x;
placePacket.yPosition = y;
placePacket.zPosition = z;
placePacket.direction = face;
placePacket.itemStack = inventory.getCurrentHeldItem();
connectionHandler.sendPacket(placePacket);
ticksWait = 4;
}
private void placeOn(BlockLocation location, int face) {
MainPlayerEntity player = bot.getPlayer();
if(player == null)
return;
PlayerInventory inventory = player.getInventory();
int x = location.getX(), y = location.getY(), z = location.getZ();
location = getOffsetBlock(location, face);
if(location == null)
return;
int originalX = location.getX(), originalY = location.getY(), originalZ = location.getZ();
player.face(x + ((originalX - x) / 2.0D) + 0.5, y + ((originalY - y) / 2.0D), z + ((originalZ - z) / 2.0D) + 0.5);
ConnectionHandler connectionHandler = bot.getConnectionHandler();
connectionHandler.sendPacket(new Packet12PlayerLook((float) player.getYaw(), (float) player.getPitch(), true));
connectionHandler.sendPacket(new Packet18Animation(player.getId(), Animation.SWING_ARM));
Packet15Place placePacket = new Packet15Place();
placePacket.xPosition = x;
placePacket.yPosition = y;
placePacket.zPosition = z;
placePacket.direction = face;
placePacket.itemStack = inventory.getCurrentHeldItem();
connectionHandler.sendPacket(placePacket);
ticksWait = 4;
}
private int getPlacementBlockFaceAt(BlockLocation location) {
int x = location.getX(), y = location.getY(), z = location.getZ();
World world = bot.getWorld();
if(!UNPLACEABLE[world.getBlockIdAt(x, y - 1, z)]) {
return 1;
} else if(!UNPLACEABLE[world.getBlockIdAt(x, y + 1, z)]) {
return 0;
} else if(!UNPLACEABLE[world.getBlockIdAt(x + 1, y, z)]) {
return 4;
} else if(!UNPLACEABLE[world.getBlockIdAt(x, y, z - 1)]) {
return 3;
} else if(!UNPLACEABLE[world.getBlockIdAt(x, y, z + 1)]) {
return 2;
} else if(!UNPLACEABLE[world.getBlockIdAt(x - 1, y, z)]) {
return 5;
} else
return -1;
}
private BlockLocation getOffsetBlock(BlockLocation location, int face) {
int x = location.getX(), y = location.getY(), z = location.getZ();
switch(face) {
case 0:
y++;
break;
case 1:
y--;
break;
case 2:
z++;
break;
case 3:
z--;
break;
case 4:
x++;
break;
case 5:
x--;
break;
default:
return null;
}
return new BlockLocation(x, y, z);
}
public StorageAction getStorageAction() {
return storageAction;
}
public void setStorageAction(StorageAction storageAction) {
this.storageAction = storageAction;
}
@Override
public TaskPriority getPriority() {
return TaskPriority.NORMAL;
}
@Override
public boolean isExclusive() {
return false;
}
@Override
public boolean ignoresExclusive() {
return false;
}
@Override
public String getName() {
return "Farm";
}
@Override
public String getOptionDescription() {
return "[<x1> <y1> <z1> <x2> <y2> <z2>]";
}
}
| false | true | public synchronized void run() {
if(currentlyBreaking != null) {
ticksSinceBreak++;
if(ticksSinceBreak > 200)
currentlyBreaking = null;
return;
}
ticksSinceBreak = 0;
TaskManager taskManager = bot.getTaskManager();
EatTask eatTask = taskManager.getTaskFor(EatTask.class);
if(eatTask.isActive())
return;
if(ticksWait > 0) {
ticksWait--;
return;
}
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return;
BlockLocation ourLocation = new BlockLocation(player.getLocation());
PlayerInventory inventory = player.getInventory();
boolean store = !inventory.contains(0);
if(!store && storageAction.equals(StorageAction.SELL) && selling)
for(int id : FARMED_ITEMS)
if(inventory.getCount(id) >= 64)
store = true;
if(store) {
System.out.println("Inventory is full!!!");
if(storageAction.equals(StorageAction.STORE)) {
if(player.getWindow() instanceof ChestInventory) {
System.out.println("Chest is open!!!");
ChestInventory chest = (ChestInventory) player.getWindow();
int freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1) {
if(currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
System.out.println("Closed chest, no spaces!!!");
ticksWait = 16;
return;
}
for(int i = 0; i < 36; i++) {
ItemStack item = chest.getItemAt(chest.getSize() + i);
if(item == null)
continue;
boolean found = false;
for(int id : FARMED_ITEMS)
if(id == item.getId())
found = true;
if(!found)
continue;
chest.selectItemAt(chest.getSize() + i);
int index = -1;
for(int j = 0; j < chest.getSize(); j++) {
if(chest.getItemAt(j) == null) {
index = j;
break;
}
}
if(index == -1)
continue;
chest.selectItemAt(index);
}
freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1 && currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
currentChest = null;
System.out.println("Closed chest!!!");
ticksWait = 16;
return;
} else {
BlockLocation[] chests = getBlocks(54, 32);
chestLoop: for(BlockLocation chest : chests) {
if(!fullChests.contains(chest) && !isChestCovered(chest)) {
BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > chest.getY())
face = 1;
else if(walk.getX() > chest.getX())
face = 5;
else if(walk.getX() < chest.getX())
face = 4;
else if(walk.getZ() > chest.getZ())
face = 3;
else if(walk.getZ() < chest.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue chestLoop;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue chestLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
if(!ourLocation.equals(closestWalk)) {
System.out.println("Walking to chest!!!");
bot.setActivity(new WalkActivity(bot, closestWalk));
return;
}
System.out.println("Opening chest!!!");
placeAt(originalWalk, face);
currentChest = chest;
ticksWait = 80;
return;
}
}
}
} else if(storageAction.equals(StorageAction.SELL)) {
if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) {
bot.say("/spawn");
ticksWait = 200;
return;
}
selling = true;
BlockLocation[] signs = getBlocks(68, 32);
signLoop: for(BlockLocation sign : signs) {
TileEntity tile = world.getTileEntityAt(sign);
if(tile == null || !(tile instanceof SignTileEntity))
continue;
SignTileEntity signTile = (SignTileEntity) tile;
String[] text = signTile.getText();
boolean found = false;
if(text[0].contains("[Sell]"))
for(int id : FARMED_ITEMS)
if(text[2].equals(Integer.toString(id)) && inventory.contains(id))
found = true;
if(!found)
continue;
if(player.getDistanceTo(sign) > 3) {
BlockLocation closestWalk = sign;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue signLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
player.walkTo(closestWalk);
System.out.println("Walking to sign @ " + sign);
return;
}
BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > sign.getY())
face = 1;
else if(walk.getX() > sign.getX())
face = 5;
else if(walk.getX() < sign.getX())
face = 4;
else if(walk.getZ() > sign.getZ())
face = 3;
else if(walk.getZ() < sign.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue;
placeOn(sign, face);
ticksWait = 4;
return;
}
}
}
BlockLocation closest = getClosestFarmable(32);
if(region != null ? !region.contains(ourLocation) : closest == null) {
bot.say("/home");
ticksWait = 200;
return;
}
if(closest == null) {
if(itemCheckWait > 0) {
itemCheckWait--;
return;
}
if(!inventory.contains(0)) {
itemCheckWait = 10;
return;
}
ItemEntity item = getClosestGroundItem(FARMED_ITEMS);
if(item != null) {
System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation());
bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation())));
} else
itemCheckWait = 10;
return;
}
itemCheckWait = 0;
System.out.println("Farming at " + closest + "!");
int id = world.getBlockIdAt(closest);
if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) {
System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest));
BlockLocation walkTo = closest;
if(id == 83)
walkTo = closest.offset(0, -1, 0);
else if(id == 86 || id == 103) {
BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid())
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
}
}
if(closestWalk == null)
return;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
return;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
walkTo = closestWalk;
}
if(!ourLocation.equals(walkTo)) {
bot.setActivity(new WalkActivity(bot, walkTo));
return;
}
breakBlock(closest);
} else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) {
if(id == 104 || id == 105) {
BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) };
for(BlockLocation dirtLocation : locations)
if(world.getBlockIdAt(dirtLocation) == 3)
closest = dirtLocation;
}
int[] tools;
if(id == 88)
tools = new int[] { 372 };
else if(id == 60)
tools = new int[] { 295 };
else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES))
tools = HOES;
// else if(inventory.contains(338) && (id == 3 || id == 12))
// tools = new int[] { 338 };
else
return;
if(!switchTo(tools))
return;
BlockLocation offset = closest.offset(0, 1, 0);
if(!ourLocation.equals(offset)) {
bot.setActivity(new WalkActivity(bot, offset));
return;
}
placeAt(offset);
ticksWait = 5;
}
}
| public synchronized void run() {
if(currentlyBreaking != null) {
ticksSinceBreak++;
if(ticksSinceBreak > 200)
currentlyBreaking = null;
return;
}
ticksSinceBreak = 0;
TaskManager taskManager = bot.getTaskManager();
EatTask eatTask = taskManager.getTaskFor(EatTask.class);
if(eatTask.isActive())
return;
if(ticksWait > 0) {
ticksWait--;
return;
}
MainPlayerEntity player = bot.getPlayer();
World world = bot.getWorld();
if(player == null || world == null)
return;
BlockLocation ourLocation = new BlockLocation(player.getLocation());
PlayerInventory inventory = player.getInventory();
boolean store = !inventory.contains(0);
if(!store && storageAction.equals(StorageAction.SELL) && selling)
for(int id : FARMED_ITEMS)
if(inventory.getCount(id) >= 64)
store = true;
if(store) {
System.out.println("Inventory is full!!!");
if(storageAction.equals(StorageAction.STORE)) {
if(player.getWindow() instanceof ChestInventory) {
System.out.println("Chest is open!!!");
ChestInventory chest = (ChestInventory) player.getWindow();
int freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1) {
if(currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
System.out.println("Closed chest, no spaces!!!");
ticksWait = 16;
return;
}
for(int i = 0; i < 36; i++) {
ItemStack item = chest.getItemAt(chest.getSize() + i);
if(item == null)
continue;
boolean found = false;
for(int id : FARMED_ITEMS)
if(id == item.getId())
found = true;
if(!found)
continue;
chest.selectItemAt(chest.getSize() + i);
int index = -1;
for(int j = 0; j < chest.getSize(); j++) {
if(chest.getItemAt(j) == null) {
index = j;
break;
}
}
if(index == -1)
continue;
chest.selectItemAt(index);
}
freeSpace = -1;
for(int i = 0; i < chest.getSize(); i++)
if(chest.getItemAt(i) == null)
freeSpace = i;
if(freeSpace == -1 && currentChest != null) {
fullChests.add(currentChest);
placeBlockAt(currentChest.offset(0, 1, 0));
currentChest = null;
}
chest.close();
currentChest = null;
System.out.println("Closed chest!!!");
ticksWait = 16;
return;
} else {
BlockLocation[] chests = getBlocks(54, 32);
chestLoop: for(BlockLocation chest : chests) {
if(!fullChests.contains(chest) && !isChestCovered(chest)) {
BlockLocation[] surrounding = new BlockLocation[] { chest.offset(0, 1, 0), chest.offset(-1, 0, 0), chest.offset(1, 0, 0), chest.offset(0, 0, -1), chest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > chest.getY())
face = 1;
else if(walk.getX() > chest.getX())
face = 5;
else if(walk.getX() < chest.getX())
face = 4;
else if(walk.getZ() > chest.getZ())
face = 3;
else if(walk.getZ() < chest.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue chestLoop;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue chestLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
if(!ourLocation.equals(closestWalk)) {
System.out.println("Walking to chest!!!");
bot.setActivity(new WalkActivity(bot, closestWalk));
return;
}
System.out.println("Opening chest!!!");
placeAt(originalWalk, face);
currentChest = chest;
ticksWait = 80;
return;
}
}
}
} else if(storageAction.equals(StorageAction.SELL)) {
if(region != null ? region.contains(ourLocation) : getClosestFarmable(32) != null) {
bot.say("/spawn");
ticksWait = 200;
return;
}
selling = true;
BlockLocation[] signs = getBlocks(68, 32);
signLoop: for(BlockLocation sign : signs) {
TileEntity tile = world.getTileEntityAt(sign);
if(tile == null || !(tile instanceof SignTileEntity))
continue;
SignTileEntity signTile = (SignTileEntity) tile;
String[] text = signTile.getText();
boolean found = false;
if(text[0].contains("[Sell]"))
for(int id : FARMED_ITEMS)
if(text[2].equals(Integer.toString(id)) && inventory.getCount(id) >= 64)
found = true;
if(!found)
continue;
if(player.getDistanceTo(sign) > 3) {
BlockLocation closestWalk = sign;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
continue signLoop;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
player.walkTo(closestWalk);
System.out.println("Walking to sign @ " + sign);
return;
}
BlockLocation[] surrounding = new BlockLocation[] { sign.offset(0, 1, 0), sign.offset(-1, 0, 0), sign.offset(1, 0, 0), sign.offset(0, 0, -1), sign.offset(0, 0, 1), sign.offset(0, -1, 0) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
int face = 0;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid() || (BlockType.getById(world.getBlockIdAt(walk.offset(0, 1, 0))).isSolid() && BlockType.getById(world.getBlockIdAt(walk.offset(0, -1, 0))).isSolid()))
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
if(walk.getY() > sign.getY())
face = 1;
else if(walk.getX() > sign.getX())
face = 5;
else if(walk.getX() < sign.getX())
face = 4;
else if(walk.getZ() > sign.getZ())
face = 3;
else if(walk.getZ() < sign.getZ())
face = 2;
else
face = 0;
}
}
if(closestWalk == null)
continue;
placeOn(sign, face);
ticksWait = 4;
return;
}
return;
}
}
BlockLocation closest = getClosestFarmable(32);
if(region != null ? !region.contains(ourLocation) : closest == null) {
bot.say("/home");
ticksWait = 200;
return;
}
if(closest == null) {
if(itemCheckWait > 0) {
itemCheckWait--;
return;
}
if(!inventory.contains(0)) {
itemCheckWait = 10;
return;
}
ItemEntity item = getClosestGroundItem(FARMED_ITEMS);
if(item != null) {
System.out.println("Item: " + item.getItem() + " Location: " + item.getLocation());
bot.setActivity(new WalkActivity(bot, new BlockLocation(item.getLocation())));
} else
itemCheckWait = 10;
return;
}
itemCheckWait = 0;
System.out.println("Farming at " + closest + "!");
int id = world.getBlockIdAt(closest);
if(id == 115 || id == 59 || id == 83 || id == 86 || id == 103) {
System.out.println("Target: " + id + "-" + world.getBlockMetadataAt(closest));
BlockLocation walkTo = closest;
if(id == 83)
walkTo = closest.offset(0, -1, 0);
else if(id == 86 || id == 103) {
BlockLocation[] surrounding = new BlockLocation[] { closest.offset(0, 1, 0), closest.offset(-1, 0, 0), closest.offset(1, 0, 0), closest.offset(0, 0, -1), closest.offset(0, 0, 1) };
BlockLocation closestWalk = null;
int closestDistance = Integer.MAX_VALUE;
for(BlockLocation walk : surrounding) {
if(BlockType.getById(world.getBlockIdAt(walk)).isSolid())
continue;
int distance = ourLocation.getDistanceToSquared(walk);
if(distance < closestDistance) {
closestWalk = walk;
closestDistance = distance;
}
}
if(closestWalk == null)
return;
BlockLocation originalWalk = closestWalk;
BlockLocation closestWalkOffset = closestWalk.offset(0, -1, 0);
while(!BlockType.getById(world.getBlockIdAt(closestWalkOffset)).isSolid()) {
closestWalk = closestWalkOffset;
if(originalWalk.getY() - closestWalkOffset.getY() > 5)
return;
closestWalkOffset = closestWalkOffset.offset(0, -1, 0);
}
walkTo = closestWalk;
}
if(!ourLocation.equals(walkTo)) {
bot.setActivity(new WalkActivity(bot, walkTo));
return;
}
breakBlock(closest);
} else if(id == 88 || id == 60 || id == 3 || id == 104 || id == 105) {
if(id == 104 || id == 105) {
BlockLocation[] locations = new BlockLocation[] { closest.offset(-1, -1, 0), closest.offset(1, -1, 0), closest.offset(0, -1, -1), closest.offset(0, -1, -1) };
for(BlockLocation dirtLocation : locations)
if(world.getBlockIdAt(dirtLocation) == 3)
closest = dirtLocation;
}
int[] tools;
if(id == 88)
tools = new int[] { 372 };
else if(id == 60)
tools = new int[] { 295 };
else if(((id == 3 && inventory.contains(295)) || id == 104 || id == 105) && inventory.contains(HOES))
tools = HOES;
// else if(inventory.contains(338) && (id == 3 || id == 12))
// tools = new int[] { 338 };
else
return;
if(!switchTo(tools))
return;
BlockLocation offset = closest.offset(0, 1, 0);
if(!ourLocation.equals(offset)) {
bot.setActivity(new WalkActivity(bot, offset));
return;
}
placeAt(offset);
ticksWait = 5;
}
}
|
diff --git a/Clock.java b/Clock.java
index a14cad6..6ce1552 100644
--- a/Clock.java
+++ b/Clock.java
@@ -1,263 +1,264 @@
import java.util.*;
import java.util.ArrayList;
import java.lang.*;
import java.io.File;
import java.io.*;
public class Clock {
private static boolean DEBUG = true; // for sterling algor.
private boolean DEBUG_OUT = false; // for internal use, comment to false
private int missPenalty = 0,
dirtyPagePenalty = 0, pageSize = 0,
vaBits = 0, paBits = 0, frameCount = 0,
numOfProcesses = 0;
private String referenceFile;
private ArrayList<Process> processList = new ArrayList<Process>();
private Process running = null;
private PageTable pageTable = null;
private boolean[] bitmap;
private ArrayList<PageTable.Page> clockStruct;
public static void main(String... arg) {
Clock clock = new Clock();
clock.run();
}
public Clock() {
readSettings("MemoryManagement.txt");
bitmap = new boolean[frameCount];
clockStruct = new ArrayList<PageTable.Page>(frameCount);
for (int i = 0; i < bitmap.length; ++i) {
bitmap[i] = false; //false is free
}
pageTable = new PageTable(pageSize);
readReference(referenceFile);
}
public void run() {
System.err.println();
int memoryCycle = 1;
System.out.println("References file: " + referenceFile
+ "\nPage size: " + pageSize
+ "\nVA size: " + vaBits
+ "\nPA size: " + paBits
+ "\nMiss penalty: " + missPenalty
+ "\nDirty page penalty: " + dirtyPagePenalty
+ "\nDebug: " + DEBUG
+ "\nFrame Count: " + frameCount
+ "\n"
+ "\nRunning Clock\n========");
while (processList.size() > 0) {
while (!checkIfReady(processList.get(0))) {
/* set top process to the next process and
push the top to the end of the queue */
Process top = processList.get(0);
processList.remove(0); // Take O(N)
processList.add(top);
} // if there's penalty on all processes this will generate an infinite loop
running = processList.get(0); // this has to change ! update Note to self
processList.remove(0); // Take O(N)
System.out.println("Running " + running.getPid());
while (running.topRef()!=null && checkRefIfValid(running.topRef())) {
int tmpBurst = running.getBurst();
while (tmpBurst > 0) {
--tmpBurst;
for (int i = 0; i < processList.size(); ++i) {
Process tmp = processList.get(i);
tmp.decPenaltyTime(); // nvr goes below 0
processList.set(i, tmp);
}
}
if(DEBUG){
System.out.print("Clock: ");
for (int i = 0; i < clockStruct.size(); ++i) {
System.out.print(i + " ");
}
System.out.print("Free frames: ");
for (int i = 0; i < bitmap.length; ++i) {
System.out.print((!bitmap[i]) ? i + " " : "");
}
System.out.println();
}
System.out.print("R/W: " + (( running.topRef().getReadOrWrite() )?"R":"W")
- + "; VA: " + running.topRef().getAddress()/pageSize
+ + "; VA: " + running.topRef().getAddress()
+ + "; Page: " + running.topRef().getAddress()/pageSize
+ "; Offset: " + running.topRef().getAddress()%pageSize
+ "; ");
System.out.println();
memoryCycle++;
running.popRef();
}
if(running.topRef()==null)break;
int freePageIndex = nextFreePage();
PageTable.Page tmpPage = pageTable.new Page(running.topRef().getAddress() >> 6);
if (freePageIndex >= 0) {
clockStruct.add(tmpPage);
running.setPenaltyTime(missPenalty);
} else {
boolean isDirty = false;
// this means loop around finding unref'ed. pages.
for (int i = 0; i < clockStruct.size(); ++i) {
//check if ref is = 0
if (clockStruct.get(i).referenced == false) {
clockStruct.set(i, tmpPage);
isDirty = true;
running.setPenaltyTime(missPenalty);
break;
}
}
if(isDirty){
clockStruct.set(0, tmpPage);
running.setPenaltyTime(missPenalty+dirtyPagePenalty);
}
}
running.popRef();// we no longer need this.
// move to the back of the queue
processList.add(running);
}
}
public int nextFreePage() {
for (int i = 0; i < bitmap.length; ++i) {
if (bitmap[i] == false) {
return i;
}
}
return -1;
}
private void readReference(String filename) {
/*
*# of processes
* process list
* pid
* burst, Defined as the number of memory references
between I/O requests.
* # of references for the process
list of references for the process.
Each reference indicates whether it was a
read or a write
*/
try {
Scanner scan = new Scanner(new File(filename));
if (scan.hasNextLine()) {
numOfProcesses = scan.nextInt();
} else {
System.out.println("Error: Nothing to read. Reference File.\n");
}
for (int i = 0; i < numOfProcesses; ++i) {
if (scan.hasNextLine()) {
int tmpPid, tmpBurst, tmpNumOfRefs;
tmpPid = scan.nextInt(); // pid
tmpBurst = scan.nextInt(); // burst
tmpNumOfRefs = scan.nextInt(); // number of references
if (DEBUG_OUT) {
System.out.println("\npid: " + tmpPid +
"\nburst: " + tmpBurst +
"\nnum of refs: " + tmpNumOfRefs);
}
ArrayList<Reference> refs = new ArrayList<Reference>();
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.isEmpty()) {
continue; // this means is an empty line, ignore.
}
if (DEBUG_OUT) {
System.out.println("\nline: " + line +
"\nsizeOfLine: " + line.length()); // output for debug
}
Scanner scanLine = new Scanner(line);
Reference reference = new Reference(scanLine.nextInt(), // address
(scanLine.hasNext("R")) // read or write
);
refs.add(reference);
}
processList.add(new Process(tmpPid, tmpBurst, tmpNumOfRefs, refs));
}
}
} catch (java.io.FileNotFoundException e) {
System.out.println("Exception in readReference(), in clock class ");
e.printStackTrace();
}
}
private void readSettings(String filename) {
/*referenceFile=references.txt
missPenalty=1
dirtyPagePenalty=0
pageSize=1024
VAbits=16
PAbits=13
frameCount=5
debug=true
*/
try {
Scanner scan = new Scanner(new File(filename));
String line, value, arg;
while (scan.hasNextLine()) {
line = scan.nextLine();
int indexEquals = line.indexOf("=");
arg = line.substring(0, indexEquals);
value = line.substring(indexEquals + 1);
if (DEBUG_OUT) {
System.out.println("in readSetting()\nargnument: " + arg + "\nvalue: " + value);
}
setValue(arg, value);
}
} catch (java.io.FileNotFoundException e) {
System.out.println("Exception in readSetting(), in clock class ");
e.printStackTrace();
}
}
private void setValue(String arg, String value) {
if (arg.equals("missPenalty")) {
missPenalty = Integer.valueOf(value);
} else if (arg.equals("debug")) {
DEBUG = Boolean.valueOf(value);
} else if (arg.equals("referenceFile")) {
referenceFile = value;
} else if (arg.equals("dirtyPagePenalty")) {
dirtyPagePenalty = Integer.valueOf(value);
} else if (arg.equals("pageSize")) {
pageSize = Integer.valueOf(value);
} else if (arg.equals("VAbits")) {
vaBits = Integer.valueOf(value);
} else if (arg.equals("PAbits")) {
paBits = Integer.valueOf(value);
} else if (arg.equals("frameCount")) {
frameCount = Integer.valueOf(value);
} else {
System.out.println("Error: Argument not found! \nArgument:" + arg + "\nValue: " + value);
}
}
boolean checkIfReady(Process process) { // true if no penalty
return (process.getPenaltyTime() == 0);
}
boolean checkRefIfValid(Reference ref) {
int VA = ref.getAddress();
int index = VA /pageSize ;
if(DEBUG_OUT){
System.out.println("checking for out of bound index is:"+index
+"\nVirtual Address: "+VA
);
}
return pageTable.getPageAtIndex(index).valid;
}
}
| true | true | public void run() {
System.err.println();
int memoryCycle = 1;
System.out.println("References file: " + referenceFile
+ "\nPage size: " + pageSize
+ "\nVA size: " + vaBits
+ "\nPA size: " + paBits
+ "\nMiss penalty: " + missPenalty
+ "\nDirty page penalty: " + dirtyPagePenalty
+ "\nDebug: " + DEBUG
+ "\nFrame Count: " + frameCount
+ "\n"
+ "\nRunning Clock\n========");
while (processList.size() > 0) {
while (!checkIfReady(processList.get(0))) {
/* set top process to the next process and
push the top to the end of the queue */
Process top = processList.get(0);
processList.remove(0); // Take O(N)
processList.add(top);
} // if there's penalty on all processes this will generate an infinite loop
running = processList.get(0); // this has to change ! update Note to self
processList.remove(0); // Take O(N)
System.out.println("Running " + running.getPid());
while (running.topRef()!=null && checkRefIfValid(running.topRef())) {
int tmpBurst = running.getBurst();
while (tmpBurst > 0) {
--tmpBurst;
for (int i = 0; i < processList.size(); ++i) {
Process tmp = processList.get(i);
tmp.decPenaltyTime(); // nvr goes below 0
processList.set(i, tmp);
}
}
if(DEBUG){
System.out.print("Clock: ");
for (int i = 0; i < clockStruct.size(); ++i) {
System.out.print(i + " ");
}
System.out.print("Free frames: ");
for (int i = 0; i < bitmap.length; ++i) {
System.out.print((!bitmap[i]) ? i + " " : "");
}
System.out.println();
}
System.out.print("R/W: " + (( running.topRef().getReadOrWrite() )?"R":"W")
+ "; VA: " + running.topRef().getAddress()/pageSize
+ "; Offset: " + running.topRef().getAddress()%pageSize
+ "; ");
System.out.println();
memoryCycle++;
running.popRef();
}
if(running.topRef()==null)break;
int freePageIndex = nextFreePage();
PageTable.Page tmpPage = pageTable.new Page(running.topRef().getAddress() >> 6);
if (freePageIndex >= 0) {
clockStruct.add(tmpPage);
running.setPenaltyTime(missPenalty);
} else {
boolean isDirty = false;
// this means loop around finding unref'ed. pages.
for (int i = 0; i < clockStruct.size(); ++i) {
//check if ref is = 0
if (clockStruct.get(i).referenced == false) {
clockStruct.set(i, tmpPage);
isDirty = true;
running.setPenaltyTime(missPenalty);
break;
}
}
if(isDirty){
clockStruct.set(0, tmpPage);
running.setPenaltyTime(missPenalty+dirtyPagePenalty);
}
}
running.popRef();// we no longer need this.
// move to the back of the queue
processList.add(running);
}
}
| public void run() {
System.err.println();
int memoryCycle = 1;
System.out.println("References file: " + referenceFile
+ "\nPage size: " + pageSize
+ "\nVA size: " + vaBits
+ "\nPA size: " + paBits
+ "\nMiss penalty: " + missPenalty
+ "\nDirty page penalty: " + dirtyPagePenalty
+ "\nDebug: " + DEBUG
+ "\nFrame Count: " + frameCount
+ "\n"
+ "\nRunning Clock\n========");
while (processList.size() > 0) {
while (!checkIfReady(processList.get(0))) {
/* set top process to the next process and
push the top to the end of the queue */
Process top = processList.get(0);
processList.remove(0); // Take O(N)
processList.add(top);
} // if there's penalty on all processes this will generate an infinite loop
running = processList.get(0); // this has to change ! update Note to self
processList.remove(0); // Take O(N)
System.out.println("Running " + running.getPid());
while (running.topRef()!=null && checkRefIfValid(running.topRef())) {
int tmpBurst = running.getBurst();
while (tmpBurst > 0) {
--tmpBurst;
for (int i = 0; i < processList.size(); ++i) {
Process tmp = processList.get(i);
tmp.decPenaltyTime(); // nvr goes below 0
processList.set(i, tmp);
}
}
if(DEBUG){
System.out.print("Clock: ");
for (int i = 0; i < clockStruct.size(); ++i) {
System.out.print(i + " ");
}
System.out.print("Free frames: ");
for (int i = 0; i < bitmap.length; ++i) {
System.out.print((!bitmap[i]) ? i + " " : "");
}
System.out.println();
}
System.out.print("R/W: " + (( running.topRef().getReadOrWrite() )?"R":"W")
+ "; VA: " + running.topRef().getAddress()
+ "; Page: " + running.topRef().getAddress()/pageSize
+ "; Offset: " + running.topRef().getAddress()%pageSize
+ "; ");
System.out.println();
memoryCycle++;
running.popRef();
}
if(running.topRef()==null)break;
int freePageIndex = nextFreePage();
PageTable.Page tmpPage = pageTable.new Page(running.topRef().getAddress() >> 6);
if (freePageIndex >= 0) {
clockStruct.add(tmpPage);
running.setPenaltyTime(missPenalty);
} else {
boolean isDirty = false;
// this means loop around finding unref'ed. pages.
for (int i = 0; i < clockStruct.size(); ++i) {
//check if ref is = 0
if (clockStruct.get(i).referenced == false) {
clockStruct.set(i, tmpPage);
isDirty = true;
running.setPenaltyTime(missPenalty);
break;
}
}
if(isDirty){
clockStruct.set(0, tmpPage);
running.setPenaltyTime(missPenalty+dirtyPagePenalty);
}
}
running.popRef();// we no longer need this.
// move to the back of the queue
processList.add(running);
}
}
|
diff --git a/src/eu/alefzero/owncloud/files/services/FileUploader.java b/src/eu/alefzero/owncloud/files/services/FileUploader.java
index a55675d..c34e79c 100644
--- a/src/eu/alefzero/owncloud/files/services/FileUploader.java
+++ b/src/eu/alefzero/owncloud/files/services/FileUploader.java
@@ -1,208 +1,209 @@
package eu.alefzero.owncloud.files.services;
import java.io.File;
import java.net.URLDecoder;
import eu.alefzero.owncloud.AccountUtils;
import eu.alefzero.owncloud.R;
import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
import eu.alefzero.owncloud.datamodel.OCFile;
import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
import eu.alefzero.owncloud.utils.OwnCloudVersion;
import eu.alefzero.webdav.OnUploadProgressListener;
import eu.alefzero.webdav.WebdavClient;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.RemoteViews;
import android.widget.Toast;
public class FileUploader extends Service implements OnDatatransferProgressListener {
public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
public static final String KEY_ACCOUNT = "ACCOUNT";
public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
public static final int UPLOAD_SINGLE_FILE = 0;
public static final int UPLOAD_MULTIPLE_FILES = 1;
private static final String TAG = "FileUploader";
private NotificationManager mNotificationManager;
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private AccountManager mAccountManager;
private Account mAccount;
private String[] mLocalPaths, mRemotePaths;
private boolean mResult;
private int mUploadType;
private Notification mNotification;
private int mTotalDataToSend, mSendData;
private int mCurrentIndexUpload, mPreviousPercent;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
uploadFile();
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread("FileUploaderThread",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
mAccountManager = AccountManager.get(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
Log.e(TAG, "Not enought data in intent provided");
return Service.START_NOT_STICKY;
}
mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
if (mUploadType == -1) {
Log.e(TAG, "Incorrect upload type provided");
return Service.START_NOT_STICKY;
}
if (mUploadType == UPLOAD_SINGLE_FILE) {
mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
mRemotePaths = new String[] { intent
.getStringExtra(KEY_REMOTE_FILE) };
} else { // mUploadType == UPLOAD_MULTIPLE_FILES
mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
}
for (int i = 0; i < mRemotePaths.length; ++i)
mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
if (mLocalPaths.length != mRemotePaths.length) {
Log.e(TAG, "Remote paths and local paths are not equal!");
return Service.START_NOT_STICKY;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return Service.START_NOT_STICKY;
}
public void run() {
if (mResult) {
Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(this, "No i kupa", Toast.LENGTH_SHORT).show();
}
}
public void uploadFile() {
String baseUrl = mAccountManager.getUserData(mAccount,
AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
String webdav_path = AccountUtils.getWebdavPath(ocVer);
Uri ocUri = Uri.parse(baseUrl + webdav_path);
String username = mAccount.name.substring(0,
mAccount.name.lastIndexOf('@'));
String password = mAccountManager.getPassword(mAccount);
FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
mTotalDataToSend = mSendData = mPreviousPercent = 0;
mNotification = new Notification(
eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
System.currentTimeMillis());
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
// dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
// BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on an upload in the notification bar
mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationManager.notify(42, mNotification);
WebdavClient wc = new WebdavClient(ocUri);
wc.allowSelfsignedCertificates();
wc.setDataTransferProgressListener(this);
wc.setCredentials(username, password);
for (int i = 0; i < mLocalPaths.length; ++i) {
File f = new File(mLocalPaths[i]);
mTotalDataToSend += f.length();
}
Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
for (int i = 0; i < mLocalPaths.length; ++i) {
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
mLocalPaths[i].substring(mLocalPaths[i]
.lastIndexOf('.') + 1));
mResult = false;
mCurrentIndexUpload = i;
if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
mResult |= true;
- OCFile new_file = new OCFile(mRemotePaths[i]);
+ String decRemotePath = URLDecoder.decode(mRemotePaths[i]);
+ OCFile new_file = new OCFile(decRemotePath); // FyleSyncAdapter and this MUST use the same encoding when creating a new OCFile
new_file.setMimetype(mimeType);
new_file.setFileLength(new File(mLocalPaths[i]).length());
new_file.setModificationTimestamp(System.currentTimeMillis());
new_file.setLastSyncDate(0);
- new_file.setStoragePath(mLocalPaths[i]);
+ new_file.setStoragePath(mLocalPaths[i]);
File f = new File(URLDecoder.decode(mRemotePaths[i]));
new_file.setParentId(storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId());
storageManager.saveFile(new_file);
}
}
// notification.contentView.setProgressBar(R.id.status_progress,
// mLocalPaths.length-1, mLocalPaths.length-1, false);
mNotificationManager.cancel(42);
run();
}
@Override
public void transferProgress(long progressRate) {
mSendData += progressRate;
int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
if (percent != mPreviousPercent) {
String text = String.format("%d%% Uploading %s file", percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
mNotification.contentView.setTextViewText(R.id.status_text, text);
mNotificationManager.notify(42, mNotification);
}
mPreviousPercent = percent;
}
}
| false | true | public void uploadFile() {
String baseUrl = mAccountManager.getUserData(mAccount,
AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
String webdav_path = AccountUtils.getWebdavPath(ocVer);
Uri ocUri = Uri.parse(baseUrl + webdav_path);
String username = mAccount.name.substring(0,
mAccount.name.lastIndexOf('@'));
String password = mAccountManager.getPassword(mAccount);
FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
mTotalDataToSend = mSendData = mPreviousPercent = 0;
mNotification = new Notification(
eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
System.currentTimeMillis());
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
// dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
// BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on an upload in the notification bar
mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationManager.notify(42, mNotification);
WebdavClient wc = new WebdavClient(ocUri);
wc.allowSelfsignedCertificates();
wc.setDataTransferProgressListener(this);
wc.setCredentials(username, password);
for (int i = 0; i < mLocalPaths.length; ++i) {
File f = new File(mLocalPaths[i]);
mTotalDataToSend += f.length();
}
Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
for (int i = 0; i < mLocalPaths.length; ++i) {
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
mLocalPaths[i].substring(mLocalPaths[i]
.lastIndexOf('.') + 1));
mResult = false;
mCurrentIndexUpload = i;
if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
mResult |= true;
OCFile new_file = new OCFile(mRemotePaths[i]);
new_file.setMimetype(mimeType);
new_file.setFileLength(new File(mLocalPaths[i]).length());
new_file.setModificationTimestamp(System.currentTimeMillis());
new_file.setLastSyncDate(0);
new_file.setStoragePath(mLocalPaths[i]);
File f = new File(URLDecoder.decode(mRemotePaths[i]));
new_file.setParentId(storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId());
storageManager.saveFile(new_file);
}
}
// notification.contentView.setProgressBar(R.id.status_progress,
// mLocalPaths.length-1, mLocalPaths.length-1, false);
mNotificationManager.cancel(42);
run();
}
| public void uploadFile() {
String baseUrl = mAccountManager.getUserData(mAccount,
AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
String webdav_path = AccountUtils.getWebdavPath(ocVer);
Uri ocUri = Uri.parse(baseUrl + webdav_path);
String username = mAccount.name.substring(0,
mAccount.name.lastIndexOf('@'));
String password = mAccountManager.getPassword(mAccount);
FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
mTotalDataToSend = mSendData = mPreviousPercent = 0;
mNotification = new Notification(
eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
System.currentTimeMillis());
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
// dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
// BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on an upload in the notification bar
mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationManager.notify(42, mNotification);
WebdavClient wc = new WebdavClient(ocUri);
wc.allowSelfsignedCertificates();
wc.setDataTransferProgressListener(this);
wc.setCredentials(username, password);
for (int i = 0; i < mLocalPaths.length; ++i) {
File f = new File(mLocalPaths[i]);
mTotalDataToSend += f.length();
}
Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
for (int i = 0; i < mLocalPaths.length; ++i) {
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
mLocalPaths[i].substring(mLocalPaths[i]
.lastIndexOf('.') + 1));
mResult = false;
mCurrentIndexUpload = i;
if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
mResult |= true;
String decRemotePath = URLDecoder.decode(mRemotePaths[i]);
OCFile new_file = new OCFile(decRemotePath); // FyleSyncAdapter and this MUST use the same encoding when creating a new OCFile
new_file.setMimetype(mimeType);
new_file.setFileLength(new File(mLocalPaths[i]).length());
new_file.setModificationTimestamp(System.currentTimeMillis());
new_file.setLastSyncDate(0);
new_file.setStoragePath(mLocalPaths[i]);
File f = new File(URLDecoder.decode(mRemotePaths[i]));
new_file.setParentId(storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId());
storageManager.saveFile(new_file);
}
}
// notification.contentView.setProgressBar(R.id.status_progress,
// mLocalPaths.length-1, mLocalPaths.length-1, false);
mNotificationManager.cancel(42);
run();
}
|
diff --git a/src/loci/slim/fit/GACurveFitter.java b/src/loci/slim/fit/GACurveFitter.java
index 36a6ab5..dd18515 100644
--- a/src/loci/slim/fit/GACurveFitter.java
+++ b/src/loci/slim/fit/GACurveFitter.java
@@ -1,520 +1,521 @@
//
// GACurveFitter.java
//
/*
SLIM Plotter application and curve fitting library for
combined spectral lifetime visualization and analysis.
Copyright (C) 2006-@year@ Curtis Rueden and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.slim.fit;
import java.util.Random;
/**
* Genetic algorithm for exponential curve fitting.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
*/
public class GACurveFitter extends CurveFitter {
// -- Fields --
protected int components;
protected double[][][] geneticData;
protected double[] fitness;
protected double currentRCSE;
protected int stallGenerations;
private double mutationFactor;
private static final boolean DEBUG = false;
private static final int STALL_GENERATIONS = 3;
private static final double STALLED_FACTOR = 2.0d;
private static final double MUTATION_CHANCE = .25d;
private static final int SPECIMENS = 25;
// Must be 0 < x < 1
private static final double INITIAL_MUTATION_FACTOR = .5;
// Must be 0 < x < 1
private static final double MUTATION_FACTOR_REDUCTION = .99;
// -- Constructor --
public GACurveFitter() {
initialize();
}
public void initialize() {
curveData = null;
components = 1;
curveEstimate = new double[components][3];
geneticData = null;
fitness = null;
currentRCSE = Double.MAX_VALUE;
stallGenerations = 0;
mutationFactor = INITIAL_MUTATION_FACTOR;
}
// -- CurveFitter methods --
/**
* iterate() runs through one iteration of whatever curve fitting
* technique this curve fitter uses. This will generally update the
* information returned by getCurve and getChiSquaredError
**/
public void iterate() {
if (currentRCSE == Double.MAX_VALUE) estimate();
// TODO: Move these out, reuse them. Synchronized?
double[][][] newGeneration = new double[SPECIMENS][components][3];
Random r = new Random();
// First make the new generation.
// If we don't have generation or fitness data, generate it from whatever
// the current estimate is.
// Additionally, if we haven't improved for a number of generations,
// shake things up.
if (geneticData == null || fitness == null ||
stallGenerations > STALL_GENERATIONS)
{
stallGenerations = 0;
mutationFactor *= MUTATION_FACTOR_REDUCTION;
for (int i = 1; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
double factor = r.nextDouble() * STALLED_FACTOR;
newGeneration[i][j][k] = curveEstimate[j][k] * factor;
}
}
}
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[0][j][k] = curveEstimate[j][k];
}
}
}
else {
// The fitness array is determined in the previous generation. It is
// actually a marker for a range for a single random number, scaled to
// 0.0-1.0. For example, if the raw fitness was {4, 3, 2, 1}, the
// fitness array would contain {.4, .7, .9, 1.0}
for (int q = 0; q < newGeneration.length; q++) {
int mother = 0;
int father = 0;
double fchance = r.nextDouble();
double mchance = r.nextDouble();
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > fchance) {
father = i;
break;
}
}
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > mchance) {
mother = i;
break;
}
}
double minfluence = r.nextDouble();
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[q][j][k] =
geneticData[mother][j][k] * minfluence +
geneticData[father][j][k] * (1.0 - minfluence);
}
}
}
for (int i = 0; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
// mutate, if necessary
if (r.nextDouble() < MUTATION_CHANCE) {
newGeneration[i][j][k] *= ((1.0 - mutationFactor) +
r.nextDouble() * (2.0 * mutationFactor));
}
}
}
}
}
geneticData = newGeneration;
double total = 0.0d;
double best = Double.MAX_VALUE;
int bestindex = -1;
stallGenerations++;
for (int i = 0; i < geneticData.length; i++) {
fitness = new double[geneticData.length];
fitness[i] = getReducedChiSquaredError(geneticData[i]);
if (fitness[i] < best) {
best = fitness[i];
bestindex = i;
}
fitness[i] = 1.0 / fitness[i];
total += fitness[i];
}
for (int i = 0; i < geneticData.length; i++) {
fitness[i] /= total;
}
if (best < currentRCSE) {
stallGenerations = 0;
currentRCSE = best;
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
curveEstimate[j][k] = geneticData[bestindex][j][k];
}
}
}
/*
System.out.println("RCSE: " + currentRCSE);
for (int j = 0; j < components; j++) {
System.out.println("a: " + curveEstimate[j][0] + " b: " +
curveEstimate[j][1] + " c: " + curveEstimate[j][2]);
}
*/
}
/**
* Sets the data to be used to generate curve estimates.
* The array is expected to be of size datapoints
**/
public void setData(int[] data) {
curveData = data;
firstindex = 0;
lastindex = data.length - 1;
}
/**
* Returns a reference to the data array.
* Does not create a copy.
*/
public int[] getData() {
return curveData;
}
/**
* Sets how many exponentials are expected to be fitted.
* Currently, more than 2 is not supported.
**/
public void setComponentCount(int numExp) {
components = numExp;
curveEstimate = new double[numExp][3];
}
// Returns the number of exponentials to be fitted.
public int getComponentCount() {
return components;
}
// Initializes the curve fitter with a starting curve estimate.
public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
- for (int i = 0; i < 5; i++) {
+ int lowBound = lowValues.length < 5 ? lowValues.length : 5;
+ for (int i = 0; i < lowBound; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
/**
* Returns the current curve estimate.
* Return size is expected to be [components][3]
* For each exponential of the form ae^-bt+c,
* [][0] is a, [1] is b, [2] is c.
**/
public double[][] getCurve() {
if (components == 1) return curveEstimate;
// Otherwise, it's 2 exponential, and we want it in ascending order
if (components == 2) {
if (curveEstimate[0][1] > curveEstimate[1][1]) {
double[][] toreturn = new double[components][3];
toreturn[0] = curveEstimate[1];
toreturn[1] = curveEstimate[0];
return toreturn;
} else {
return curveEstimate;
}
}
return null;
}
/**
* Sets the current curve estimate, useful if information about the
* curve is already known.
* See getCurve for information about the array to pass.
**/
public void setCurve(double[][] curve) {
if (curve.length != components) {
throw new IllegalArgumentException("Incorrect number of components.");
}
if (curve[0].length != 3) {
throw new IllegalArgumentException(
"Incorrect number of elements per degree.");
}
curveEstimate = curve;
currentRCSE = getReducedChiSquaredError();
}
public void setFirst(int index) {
firstindex = index;
}
public void setLast(int index) {
lastindex = index;
}
}
| true | true | public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
for (int i = 0; i < 5; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
| public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
int lowBound = lowValues.length < 5 ? lowValues.length : 5;
for (int i = 0; i < lowBound; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
|
diff --git a/src/main/java/ru/skalodrom_rf/EmailSender.java b/src/main/java/ru/skalodrom_rf/EmailSender.java
index 2db8d28..7d87407 100644
--- a/src/main/java/ru/skalodrom_rf/EmailSender.java
+++ b/src/main/java/ru/skalodrom_rf/EmailSender.java
@@ -1,53 +1,55 @@
package ru.skalodrom_rf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.skalodrom_rf.model.User;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.InputStream;
import java.util.Properties;
/**.*/
public class EmailSender {
private static final Logger LOG= LoggerFactory.getLogger(EmailSender.class);
public void sendMessage(User to, String subject,String text){
try{
final Properties props= new Properties();
final InputStream stream = getClass().getClassLoader().getResourceAsStream("mail.properties");
props.load(stream);
Authenticator auth = new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
final String uname = (String)props.get("rf.skalodrom.mail.username");
final String upassword = (String)props.get("rf.skalodrom.mail.password");
return new PasswordAuthentication(uname, upassword);
}
};
final Session mailSession = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to.getProfile().getEmail()));
message.setSubject(subject);
+ message.setHeader("Content-Type","text/plain; charset=\"utf-8\"");
+ message.setHeader("Content-Transfer-Encoding", "quoted-printable");
message.setText(text);
Transport.send(message);
LOG.info("email message to "+to.getProfile().getEmail()+" sended");
}catch(Exception ex){
String msg="email not sended to ["+to.getLogin()+"] with subject=["+subject+"] with text=["+text+"]";
LOG.error(msg,ex);
}
}
}
| true | true | public void sendMessage(User to, String subject,String text){
try{
final Properties props= new Properties();
final InputStream stream = getClass().getClassLoader().getResourceAsStream("mail.properties");
props.load(stream);
Authenticator auth = new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
final String uname = (String)props.get("rf.skalodrom.mail.username");
final String upassword = (String)props.get("rf.skalodrom.mail.password");
return new PasswordAuthentication(uname, upassword);
}
};
final Session mailSession = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to.getProfile().getEmail()));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
LOG.info("email message to "+to.getProfile().getEmail()+" sended");
}catch(Exception ex){
String msg="email not sended to ["+to.getLogin()+"] with subject=["+subject+"] with text=["+text+"]";
LOG.error(msg,ex);
}
}
| public void sendMessage(User to, String subject,String text){
try{
final Properties props= new Properties();
final InputStream stream = getClass().getClassLoader().getResourceAsStream("mail.properties");
props.load(stream);
Authenticator auth = new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
final String uname = (String)props.get("rf.skalodrom.mail.username");
final String upassword = (String)props.get("rf.skalodrom.mail.password");
return new PasswordAuthentication(uname, upassword);
}
};
final Session mailSession = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to.getProfile().getEmail()));
message.setSubject(subject);
message.setHeader("Content-Type","text/plain; charset=\"utf-8\"");
message.setHeader("Content-Transfer-Encoding", "quoted-printable");
message.setText(text);
Transport.send(message);
LOG.info("email message to "+to.getProfile().getEmail()+" sended");
}catch(Exception ex){
String msg="email not sended to ["+to.getLogin()+"] with subject=["+subject+"] with text=["+text+"]";
LOG.error(msg,ex);
}
}
|
diff --git a/main/src/cgeo/geocaching/export/GpxExport.java b/main/src/cgeo/geocaching/export/GpxExport.java
index e6b52bcf2..ab2e28156 100644
--- a/main/src/cgeo/geocaching/export/GpxExport.java
+++ b/main/src/cgeo/geocaching/export/GpxExport.java
@@ -1,175 +1,175 @@
package cgeo.geocaching.export;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.R;
import cgeo.geocaching.Settings;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.utils.AsyncTaskWithProgress;
import cgeo.geocaching.utils.Log;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
class GpxExport extends AbstractExport {
protected GpxExport() {
super(getString(R.string.export_gpx));
}
@Override
public void export(final List<Geocache> caches, final Activity activity) {
final String[] geocodes = getGeocodes(caches);
if (null == activity) {
// No activity given, so no user interaction possible.
// Start export with default parameters.
new ExportTask(null).execute(geocodes);
} else {
// Show configuration dialog
getExportDialog(geocodes, activity).show();
}
}
private Dialog getExportDialog(final String[] geocodes, final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// AlertDialog has always dark style, so we have to apply it as well always
final View layout = View.inflate(new ContextThemeWrapper(activity, R.style.dark), R.layout.gpx_export_dialog, null);
builder.setView(layout);
final TextView text = (TextView) layout.findViewById(R.id.info);
text.setText(getString(R.string.export_gpx_info, Settings.getGpxExportDir()));
final CheckBox shareOption = (CheckBox) layout.findViewById(R.id.share);
shareOption.setChecked(Settings.getShareAfterExport());
shareOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShareAfterExport(shareOption.isChecked());
}
});
builder.setPositiveButton(R.string.export, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
new ExportTask(activity).execute(geocodes);
}
});
return builder.create();
}
private static String[] getGeocodes(final List<Geocache> caches) {
final ArrayList<String> allGeocodes = new ArrayList<String>(caches.size());
for (final Geocache geocache : caches) {
allGeocodes.add(geocache.getGeocode());
}
return allGeocodes.toArray(new String[allGeocodes.size()]);
}
protected class ExportTask extends AsyncTaskWithProgress<String, File> {
private final Activity activity;
/**
* Instantiates and configures the task for exporting field notes.
*
* @param activity
* optional: Show a progress bar and toasts
*/
public ExportTask(final Activity activity) {
super(activity, getProgressTitle());
this.activity = activity;
}
@Override
protected File doInBackgroundInternal(String[] geocodes) {
// quick check for being able to write the GPX file
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
final List<String> allGeocodes = new ArrayList<String>(Arrays.asList(geocodes));
setMessage(cgeoapplication.getInstance().getResources().getQuantityString(R.plurals.cache_counts, allGeocodes.size(), allGeocodes.size()));
final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
final File exportFile = new File(Settings.getGpxExportDir() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx");
BufferedWriter writer = null;
try {
final File exportLocation = new File(Settings.getGpxExportDir());
exportLocation.mkdirs();
writer = new BufferedWriter(new FileWriter(exportFile));
new GpxSerializer().writeGPX(allGeocodes, writer, new GpxSerializer.ProgressListener() {
@Override
public void publishProgress(int countExported) {
- this.publishProgress(countExported);
+ ExportTask.this.publishProgress(countExported);
}
});
} catch (final Exception e) {
Log.e("GpxExport.ExportTask export", e);
if (writer != null) {
try {
writer.close();
} catch (final IOException e1) {
// Ignore double error
}
}
// delete partial gpx file on error
if (exportFile.exists()) {
exportFile.delete();
}
return null;
}
return exportFile;
}
@Override
protected void onPostExecuteInternal(final File exportFile) {
if (null != activity) {
if (exportFile != null) {
ActivityMixin.showToast(activity, getName() + ' ' + getString(R.string.export_exportedto) + ": " + exportFile.toString());
if (Settings.getShareAfterExport()) {
final Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(exportFile));
shareIntent.setType("application/xml");
activity.startActivity(Intent.createChooser(shareIntent, getString(R.string.export_gpx_to)));
}
} else {
ActivityMixin.showToast(activity, getString(R.string.export_failed));
}
}
}
}
}
| true | true | protected File doInBackgroundInternal(String[] geocodes) {
// quick check for being able to write the GPX file
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
final List<String> allGeocodes = new ArrayList<String>(Arrays.asList(geocodes));
setMessage(cgeoapplication.getInstance().getResources().getQuantityString(R.plurals.cache_counts, allGeocodes.size(), allGeocodes.size()));
final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
final File exportFile = new File(Settings.getGpxExportDir() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx");
BufferedWriter writer = null;
try {
final File exportLocation = new File(Settings.getGpxExportDir());
exportLocation.mkdirs();
writer = new BufferedWriter(new FileWriter(exportFile));
new GpxSerializer().writeGPX(allGeocodes, writer, new GpxSerializer.ProgressListener() {
@Override
public void publishProgress(int countExported) {
this.publishProgress(countExported);
}
});
} catch (final Exception e) {
Log.e("GpxExport.ExportTask export", e);
if (writer != null) {
try {
writer.close();
} catch (final IOException e1) {
// Ignore double error
}
}
// delete partial gpx file on error
if (exportFile.exists()) {
exportFile.delete();
}
return null;
}
return exportFile;
}
| protected File doInBackgroundInternal(String[] geocodes) {
// quick check for being able to write the GPX file
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
final List<String> allGeocodes = new ArrayList<String>(Arrays.asList(geocodes));
setMessage(cgeoapplication.getInstance().getResources().getQuantityString(R.plurals.cache_counts, allGeocodes.size(), allGeocodes.size()));
final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
final File exportFile = new File(Settings.getGpxExportDir() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx");
BufferedWriter writer = null;
try {
final File exportLocation = new File(Settings.getGpxExportDir());
exportLocation.mkdirs();
writer = new BufferedWriter(new FileWriter(exportFile));
new GpxSerializer().writeGPX(allGeocodes, writer, new GpxSerializer.ProgressListener() {
@Override
public void publishProgress(int countExported) {
ExportTask.this.publishProgress(countExported);
}
});
} catch (final Exception e) {
Log.e("GpxExport.ExportTask export", e);
if (writer != null) {
try {
writer.close();
} catch (final IOException e1) {
// Ignore double error
}
}
// delete partial gpx file on error
if (exportFile.exists()) {
exportFile.delete();
}
return null;
}
return exportFile;
}
|
diff --git a/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java b/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java
index 6458278d..bc91e6de 100644
--- a/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java
+++ b/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java
@@ -1,171 +1,171 @@
/* Copyright 2005-2006 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.controller.multipart;
import net.sourceforge.stripes.controller.FileUploadLimitExceededException;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.exception.StripesRuntimeException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.File;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* <p>Default implementation of a factory for MultipartWrappers. Looks up a class name in
* Configuration under the key specified by {@link #WRAPPER_CLASS_NAME}. If no class
* name is configured, defaults to the {@link CosMultipartWrapper}. An additional configuration
* parameter is supported to specify the maximum post size allowable.</p>
*
* @author Tim Fennell
* @since Stripes 1.4
*/
public class DefaultMultipartWrapperFactory implements MultipartWrapperFactory {
/** The configuration key used to lookup the implementation of MultipartWrapper. */
public static final String WRAPPER_CLASS_NAME = "MultipartWrapper.Class";
/** The names of the MultipartWrapper classes that will be tried if no other is specified. */
public static final String[] BUNDLED_IMPLEMENTATIONS = {
"net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper",
"net.sourceforge.stripes.controller.multipart.CosMultipartWrapper" };
/** Key used to lookup the name of the maximum post size. */
public static final String MAX_POST = "FileUpload.MaximumPostSize";
private static final Log log = Log.getInstance(DefaultMultipartWrapperFactory.class);
// Instance level fields
private Configuration configuration;
private Class<? extends MultipartWrapper> multipartClass;
private long maxPostSizeInBytes = 1024 * 1024 * 10; // Defaults to 10MB
private File temporaryDirectory;
/** Get the configuration object that was passed into {@link #init(Configuration)}. */
protected Configuration getConfiguration() {
return configuration;
}
/**
* Invoked directly after instantiation to allow the configured component to perform one time
* initialization. Components are expected to fail loudly if they are not going to be in a
* valid state after initialization.
*
* @param config the Configuration object being used by Stripes
* @throws Exception should be thrown if the component cannot be configured well enough to use.
*/
@SuppressWarnings("unchecked")
public void init(Configuration config) throws Exception {
this.configuration = config;
// Determine which class we're using
this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class);
if (this.multipartClass == null) {
// It wasn't defined in web.xml so we'll try the bundled MultipartWrappers
for (String className : BUNDLED_IMPLEMENTATIONS) {
try {
this.multipartClass = ((Class<? extends MultipartWrapper>) Class
.forName(className));
break;
}
catch (Throwable t) {
log.debug(getClass().getSimpleName(), " not using ", className,
" because it failed to load. This likely means the supporting ",
"file upload library is not present on the classpath.");
}
}
}
// Log the name of the class we'll be using or a warning if none could be loaded
if (this.multipartClass == null) {
log.warn("No ", MultipartWrapper.class.getSimpleName(),
" implementation could be loaded");
}
else {
log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class
.getSimpleName(), " implementation.");
}
// Figure out where the temp directory is, and store that info
File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
if (tempDir != null) {
this.temporaryDirectory = tempDir;
}
else {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir != null) {
this.temporaryDirectory = new File(tmpDir).getAbsoluteFile();
}
else {
log.warn("The tmpdir system property was null! File uploads will probably fail. ",
"This is normal if you are running on Google App Engine as it doesn't allow ",
"file system write access.");
}
}
// See if a maximum post size was configured
String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST);
if (limit != null) {
Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*");
Matcher matcher = pattern.matcher(limit);
if (!matcher.matches()) {
log.error("Did not understand value of configuration parameter ", MAX_POST,
" You supplied: ", limit, ". Valid values are any string of numbers ",
"optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ",
"Default value of ", this.maxPostSizeInBytes, " bytes will be used instead.");
}
else {
String digits = matcher.group(1);
String suffix = matcher.group(2).toLowerCase();
- int number = Integer.parseInt(digits);
+ long number = Long.parseLong(digits);
if ("k".equals(suffix)) { number = number * 1024; }
else if ("m".equals(suffix)) { number = number * 1024 * 1024; }
else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; }
this.maxPostSizeInBytes = number;
log.info("Configured file upload post size limit: ", number, " bytes.");
}
}
}
/**
* Wraps the request in an appropriate implementation of MultipartWrapper that is capable of
* providing access to request parameters and any file parts contained within the request.
*
* @param request an active HttpServletRequest
* @return an implementation of the appropriate wrapper
* @throws IOException if encountered when consuming the contents of the request
* @throws FileUploadLimitExceededException if the post size of the request exceeds any
* configured limits
*/
public MultipartWrapper wrap(HttpServletRequest request) throws IOException, FileUploadLimitExceededException {
try {
MultipartWrapper wrapper = getConfiguration().getObjectFactory().newInstance(
this.multipartClass);
wrapper.build(request, this.temporaryDirectory, this.maxPostSizeInBytes);
return wrapper;
}
catch (IOException ioe) { throw ioe; }
catch (FileUploadLimitExceededException fulee) { throw fulee; }
catch (Exception e) {
throw new StripesRuntimeException
("Could not construct a MultipartWrapper for the current request.", e);
}
}
}
| true | true | public void init(Configuration config) throws Exception {
this.configuration = config;
// Determine which class we're using
this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class);
if (this.multipartClass == null) {
// It wasn't defined in web.xml so we'll try the bundled MultipartWrappers
for (String className : BUNDLED_IMPLEMENTATIONS) {
try {
this.multipartClass = ((Class<? extends MultipartWrapper>) Class
.forName(className));
break;
}
catch (Throwable t) {
log.debug(getClass().getSimpleName(), " not using ", className,
" because it failed to load. This likely means the supporting ",
"file upload library is not present on the classpath.");
}
}
}
// Log the name of the class we'll be using or a warning if none could be loaded
if (this.multipartClass == null) {
log.warn("No ", MultipartWrapper.class.getSimpleName(),
" implementation could be loaded");
}
else {
log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class
.getSimpleName(), " implementation.");
}
// Figure out where the temp directory is, and store that info
File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
if (tempDir != null) {
this.temporaryDirectory = tempDir;
}
else {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir != null) {
this.temporaryDirectory = new File(tmpDir).getAbsoluteFile();
}
else {
log.warn("The tmpdir system property was null! File uploads will probably fail. ",
"This is normal if you are running on Google App Engine as it doesn't allow ",
"file system write access.");
}
}
// See if a maximum post size was configured
String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST);
if (limit != null) {
Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*");
Matcher matcher = pattern.matcher(limit);
if (!matcher.matches()) {
log.error("Did not understand value of configuration parameter ", MAX_POST,
" You supplied: ", limit, ". Valid values are any string of numbers ",
"optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ",
"Default value of ", this.maxPostSizeInBytes, " bytes will be used instead.");
}
else {
String digits = matcher.group(1);
String suffix = matcher.group(2).toLowerCase();
int number = Integer.parseInt(digits);
if ("k".equals(suffix)) { number = number * 1024; }
else if ("m".equals(suffix)) { number = number * 1024 * 1024; }
else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; }
this.maxPostSizeInBytes = number;
log.info("Configured file upload post size limit: ", number, " bytes.");
}
}
}
| public void init(Configuration config) throws Exception {
this.configuration = config;
// Determine which class we're using
this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class);
if (this.multipartClass == null) {
// It wasn't defined in web.xml so we'll try the bundled MultipartWrappers
for (String className : BUNDLED_IMPLEMENTATIONS) {
try {
this.multipartClass = ((Class<? extends MultipartWrapper>) Class
.forName(className));
break;
}
catch (Throwable t) {
log.debug(getClass().getSimpleName(), " not using ", className,
" because it failed to load. This likely means the supporting ",
"file upload library is not present on the classpath.");
}
}
}
// Log the name of the class we'll be using or a warning if none could be loaded
if (this.multipartClass == null) {
log.warn("No ", MultipartWrapper.class.getSimpleName(),
" implementation could be loaded");
}
else {
log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class
.getSimpleName(), " implementation.");
}
// Figure out where the temp directory is, and store that info
File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
if (tempDir != null) {
this.temporaryDirectory = tempDir;
}
else {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir != null) {
this.temporaryDirectory = new File(tmpDir).getAbsoluteFile();
}
else {
log.warn("The tmpdir system property was null! File uploads will probably fail. ",
"This is normal if you are running on Google App Engine as it doesn't allow ",
"file system write access.");
}
}
// See if a maximum post size was configured
String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST);
if (limit != null) {
Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*");
Matcher matcher = pattern.matcher(limit);
if (!matcher.matches()) {
log.error("Did not understand value of configuration parameter ", MAX_POST,
" You supplied: ", limit, ". Valid values are any string of numbers ",
"optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ",
"Default value of ", this.maxPostSizeInBytes, " bytes will be used instead.");
}
else {
String digits = matcher.group(1);
String suffix = matcher.group(2).toLowerCase();
long number = Long.parseLong(digits);
if ("k".equals(suffix)) { number = number * 1024; }
else if ("m".equals(suffix)) { number = number * 1024 * 1024; }
else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; }
this.maxPostSizeInBytes = number;
log.info("Configured file upload post size limit: ", number, " bytes.");
}
}
}
|
diff --git a/src/de/blau/android/osm/Server.java b/src/de/blau/android/osm/Server.java
index 9b6011e..80e9e8a 100755
--- a/src/de/blau/android/osm/Server.java
+++ b/src/de/blau/android/osm/Server.java
@@ -1,296 +1,298 @@
package de.blau.android.osm;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import de.blau.android.exception.OsmException;
import de.blau.android.exception.OsmIOException;
import de.blau.android.exception.OsmServerException;
import de.blau.android.util.Base64;
/**
* @author mb
*/
public class Server {
/**
* Location of OSM API
*/
private static final String SERVER_URL = "http://api.openstreetmap.org";
/**
* Timeout for connections in milliseconds.
*/
private static final int TIMEOUT = 10 * 1000;
/**
* username for write-access on the server.
*/
private final String username;
/**
* password for write-access on the server.
*/
private final String password;
/**
* <a href="http://wiki.openstreetmap.org/wiki/API">API</a>-Version.
*/
private final String version = "0.5";
/**
* Path to api with trailing slash.
*/
private final String path = "/api/" + version + "/";
/**
* Tag with "created_by"-key to identify edits made by this editor.
*/
private final Tag createdByTag;
/**
* The opening root element for the XML file transferring to the server.
*/
private final String rootOpen;
/**
* The closing root element for the XML file transferring to the server.
*/
private static final String rootClose = "</osm>";
/**
* Constructor. Sets {@link #rootOpen} and {@link #createdByTag}.
*
* @param username
* @param password
* @param generator the name of the editor.
*/
public Server(final String username, final String password, final String generator) {
this.password = password;
this.username = username;
rootOpen = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"" + version + "\" generator=\""
+ generator + "\">\n";
createdByTag = new Tag("created_by", generator);
}
/**
* @param area
* @return
* @throws IOException
* @throws OsmServerException
*/
public InputStream getStreamForBox(final BoundingBox box) throws OsmServerException, IOException {
URL url = new URL(SERVER_URL + path + "map?bbox=" + box.toApiString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
boolean isServerGzipEnabled = false;
//--Start: header not yet send
con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
con.setRequestProperty("Accept-Encoding", "gzip");
//--Start: got response header
isServerGzipEnabled = "gzip".equals(con.getHeaderField("Content-encoding"));
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
- throw new OsmServerException(con.getResponseCode(), "The API server does not except the request: " + con);
+ throw new OsmServerException(con.getResponseCode(),
+ "The API server does not except the request: " + con + ", responce code: "
+ + con.getResponseCode());
}
if (isServerGzipEnabled) {
return new GZIPInputStream(con.getInputStream());
} else {
return con.getInputStream();
}
}
/**
* Sends an delete-request to the server.
*
* @param elem the element which should be deleted.
* @return true when the server indicates the successful deletion (HTTP 200), otherwise false.
* @throws MalformedURLException
* @throws ProtocolException
* @throws IOException
*/
public boolean deleteElement(final OsmElement elem) throws MalformedURLException, ProtocolException, IOException {
HttpURLConnection connection = null;
try {
connection = openConnectionForWriteAccess(getDeleteUrl(elem), "DELETE");
checkResponseCode(connection);
} finally {
disconnect(connection);
}
return true;
}
/**
* @return
*/
public boolean isLoginSet() {
return username != null && password != null && !username.equals("") && !username.equals("");
}
/**
* @param connection
*/
private static void disconnect(final HttpURLConnection connection) {
if (connection != null) {
connection.disconnect();
}
}
public boolean updateElement(final OsmElement elem) throws MalformedURLException, ProtocolException, IOException {
HttpURLConnection connection = null;
elem.addOrUpdateTag(createdByTag);
String xml = encloseRoot(elem);
try {
connection = openConnectionForWriteAccess(getUpdateUrl(elem), "PUT");
sendPayload(connection, xml);
checkResponseCode(connection);
} finally {
disconnect(connection);
}
return true;
}
/**
* @param connection
* @param xml
* @throws OsmIOException
*/
private void sendPayload(final HttpURLConnection connection, final String xml) throws OsmIOException {
connection.setFixedLengthStreamingMode(xml.getBytes().length);
OutputStreamWriter out = null;
try {
out = new OutputStreamWriter(connection.getOutputStream(), Charset.defaultCharset());
out.write(xml);
out.flush();
} catch (IOException e) {
throw new OsmIOException("Could not send data to server");
} finally {
close(out);
}
}
/**
* @param elem
* @param xml
* @return
* @throws IOException
* @throws MalformedURLException
* @throws ProtocolException
*/
private HttpURLConnection openConnectionForWriteAccess(final URL url, final String requestMethod)
throws IOException, MalformedURLException, ProtocolException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
connection.setRequestProperty("Authorization", "Basic " + Base64.encode(username + ":" + password));
connection.setRequestMethod(requestMethod);
connection.setDoOutput(true);
connection.setDoInput(true);
return connection;
}
public int createElement(final OsmElement elem) throws MalformedURLException, ProtocolException, IOException {
int osmId = -1;
HttpURLConnection connection = null;
InputStream in = null;
elem.addOrUpdateTag(createdByTag);
String xml = encloseRoot(elem);
try {
connection = openConnectionForWriteAccess(getCreationUrl(elem), "PUT");
sendPayload(connection, xml);
checkResponseCode(connection);
in = connection.getInputStream();
osmId = Integer.parseInt(readLine(in));
} finally {
disconnect(connection);
close(in);
}
return osmId;
}
/**
* @param connection
* @throws IOException
* @throws OsmException
*/
private void checkResponseCode(final HttpURLConnection connection) throws IOException, OsmException {
int responsecode;
responsecode = connection.getResponseCode();
if (responsecode != HttpURLConnection.HTTP_OK) {
InputStream in = connection.getErrorStream();
throw new OsmServerException(responsecode, "ErrorMessage: " + readStream(in));
}
}
private static String readStream(final InputStream in) {
String res = "";
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in), 8000);
String line = null;
try {
while ((line = reader.readLine()) != null) {
res += line;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
}
private static String readLine(final InputStream in) {
//TODO: Optimize? -> no Reader
BufferedReader reader = new BufferedReader(new InputStreamReader(in), 9);
String res = null;
try {
res = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
static public void close(final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private URL getCreationUrl(final OsmElement elem) throws MalformedURLException {
return new URL(SERVER_URL + path + elem.getName() + "/create");
}
private URL getUpdateUrl(final OsmElement elem) throws MalformedURLException {
return new URL(SERVER_URL + path + elem.getName() + "/" + elem.getOsmId());
}
private URL getDeleteUrl(final OsmElement elem) throws MalformedURLException {
return getUpdateUrl(elem);
}
private String encloseRoot(final OsmElement elem) {
return rootOpen + elem.toXml() + rootClose;
}
}
| true | true | public InputStream getStreamForBox(final BoundingBox box) throws OsmServerException, IOException {
URL url = new URL(SERVER_URL + path + "map?bbox=" + box.toApiString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
boolean isServerGzipEnabled = false;
//--Start: header not yet send
con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
con.setRequestProperty("Accept-Encoding", "gzip");
//--Start: got response header
isServerGzipEnabled = "gzip".equals(con.getHeaderField("Content-encoding"));
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new OsmServerException(con.getResponseCode(), "The API server does not except the request: " + con);
}
if (isServerGzipEnabled) {
return new GZIPInputStream(con.getInputStream());
} else {
return con.getInputStream();
}
}
| public InputStream getStreamForBox(final BoundingBox box) throws OsmServerException, IOException {
URL url = new URL(SERVER_URL + path + "map?bbox=" + box.toApiString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
boolean isServerGzipEnabled = false;
//--Start: header not yet send
con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
con.setRequestProperty("Accept-Encoding", "gzip");
//--Start: got response header
isServerGzipEnabled = "gzip".equals(con.getHeaderField("Content-encoding"));
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new OsmServerException(con.getResponseCode(),
"The API server does not except the request: " + con + ", responce code: "
+ con.getResponseCode());
}
if (isServerGzipEnabled) {
return new GZIPInputStream(con.getInputStream());
} else {
return con.getInputStream();
}
}
|
diff --git a/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java b/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java
index 1418e857..2ecff3d5 100755
--- a/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java
+++ b/core/src/main/java/org/mule/galaxy/impl/jcr/UserDetailsWrapper.java
@@ -1,108 +1,108 @@
package org.mule.galaxy.impl.jcr;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import javax.naming.directory.Attributes;
import javax.naming.ldap.Control;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.ldap.LdapUserDetails;
import org.mule.galaxy.security.Permission;
import org.mule.galaxy.security.User;
public class UserDetailsWrapper implements LdapUserDetails {
private User user;
private String password;
private Set<Permission> permissions;
private GrantedAuthority[] authorities;
private Attributes attributes;
private Control[] controls;
private String userDn;
public UserDetailsWrapper(User user, Set<Permission> set, String password) {
super();
this.user = user;
this.permissions = set;
this.password = password;
}
public User getUser() {
return user;
}
public GrantedAuthority[] getAuthorities() {
if (authorities == null) {
Object[] pArray = permissions.toArray();
authorities = new GrantedAuthority[pArray.length+1];
for (int i = 0; i < pArray.length; i++) {
authorities[i] = new GrantedAuthorityImpl(pArray[i].toString());
}
- authorities[pArray.length+1] = new GrantedAuthorityImpl("role_user");
+ authorities[pArray.length] = new GrantedAuthorityImpl("role_user");
}
return authorities;
}
public String getPassword() {
return password;
}
public String getUsername() {
return user.getUsername();
}
public boolean isAccountNonExpired() {
return user.isEnabled();
}
public boolean isAccountNonLocked() {
return user.isEnabled();
}
public boolean isCredentialsNonExpired() {
return user.isEnabled();
}
public boolean isEnabled() {
// TODO Auto-generated method stub
return user.isEnabled();
}
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
public Control[] getControls() {
return controls;
}
public void setControls(Control[] controls) {
this.controls = controls;
}
public String getDn() {
return userDn;
}
public void setDn(String dn) {
userDn = dn;
}
public void setAuthorities(GrantedAuthority[] auths) {
ArrayList list = new ArrayList(Arrays.asList(auths));
list.add(new GrantedAuthorityImpl("role_user"));
authorities = (GrantedAuthority[]) list.toArray(new GrantedAuthority[0]);
}
public void setPermissions(Set<Permission> set) {
permissions = set;
}
}
| true | true | public GrantedAuthority[] getAuthorities() {
if (authorities == null) {
Object[] pArray = permissions.toArray();
authorities = new GrantedAuthority[pArray.length+1];
for (int i = 0; i < pArray.length; i++) {
authorities[i] = new GrantedAuthorityImpl(pArray[i].toString());
}
authorities[pArray.length+1] = new GrantedAuthorityImpl("role_user");
}
return authorities;
}
| public GrantedAuthority[] getAuthorities() {
if (authorities == null) {
Object[] pArray = permissions.toArray();
authorities = new GrantedAuthority[pArray.length+1];
for (int i = 0; i < pArray.length; i++) {
authorities[i] = new GrantedAuthorityImpl(pArray[i].toString());
}
authorities[pArray.length] = new GrantedAuthorityImpl("role_user");
}
return authorities;
}
|
diff --git a/src/core/org/apache/hadoop/security/UserGroupInformation.java b/src/core/org/apache/hadoop/security/UserGroupInformation.java
index 0e4f54dde..a31128809 100644
--- a/src/core/org/apache/hadoop/security/UserGroupInformation.java
+++ b/src/core/org/apache/hadoop/security/UserGroupInformation.java
@@ -1,597 +1,597 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.security;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import javax.security.auth.spi.LoginModule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import com.sun.security.auth.NTUserPrincipal;
import com.sun.security.auth.UnixPrincipal;
import com.sun.security.auth.module.Krb5LoginModule;
/**
* User and group information for Hadoop.
* This class wraps around a JAAS Subject and provides methods to determine the
* user's username and groups. It supports both the Windows, Unix and Kerberos
* login modules.
*/
public class UserGroupInformation {
private static final Log LOG = LogFactory.getLog(UserGroupInformation.class);
private static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
/**
* A login module that looks at the Kerberos, Unix, or Windows principal and
* adds the corresponding UserName.
*/
public static class HadoopLoginModule implements LoginModule {
private Subject subject;
@Override
public boolean abort() throws LoginException {
return true;
}
private <T extends Principal> T getCanonicalUser(Class<T> cls) {
for(T user: subject.getPrincipals(cls)) {
return user;
}
return null;
}
@Override
public boolean commit() throws LoginException {
Principal user = null;
// if we are using kerberos, try it out
if (useKerberos) {
user = getCanonicalUser(KerberosPrincipal.class);
}
// if we don't have a kerberos user, use the OS user
if (user == null) {
user = getCanonicalUser(OS_PRINCIPAL_CLASS);
}
// if we found the user, add our principal
if (user != null) {
subject.getPrincipals().add(new User(user.getName()));
return true;
}
LOG.error("Can't find user in " + subject);
throw new LoginException("Can't find user name");
}
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
}
@Override
public boolean login() throws LoginException {
return true;
}
@Override
public boolean logout() throws LoginException {
return true;
}
}
/** Are the static variables that depend on configuration initialized? */
private static boolean isInitialized = false;
/** Should we use Kerberos configuration? */
private static boolean useKerberos;
/** Server-side groups fetching service */
private static Groups groups;
/**Environment variable pointing to the token cache file*/
public static final String HADOOP_TOKEN_FILE_LOCATION =
"HADOOP_TOKEN_FILE_LOCATION";
/**
* A method to initialize the fields that depend on a configuration.
* Must be called before useKerberos or groups is used.
*/
private static synchronized void ensureInitialized() {
if (!isInitialized) {
initialize(new Configuration());
}
}
/**
* Set the configuration values for UGI.
* @param conf the configuration to use
*/
private static synchronized void initialize(Configuration conf) {
String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
- if ("simple".equals(value)) {
+ if (value == null || "simple".equals(value)) {
useKerberos = false;
- } else if (value == null || "kerberos".equals(value)) {
+ } else if ("kerberos".equals(value)) {
useKerberos = true;
} else {
throw new IllegalArgumentException("Invalid attribute value for " +
HADOOP_SECURITY_AUTHENTICATION +
" of " + value);
}
// If we haven't set up testing groups, use the configuration to find it
if (!(groups instanceof TestingGroups)) {
groups = Groups.getUserToGroupsMappingService(conf);
}
// Set the configuration for JAAS to be the Hadoop configuration.
// This is done here rather than a static initializer to avoid a
// circular dependence.
javax.security.auth.login.Configuration.setConfiguration
(new HadoopConfiguration());
isInitialized = true;
}
/**
* Set the static configuration for UGI.
* In particular, set the security authentication mechanism and the
* group look up service.
* @param conf the configuration to use
*/
public static void setConfiguration(Configuration conf) {
initialize(conf);
}
/**
* Determine if UserGroupInformation is using Kerberos to determine
* user identities or is relying on simple authentication
*
* @return true if UGI is working in a secure environment
*/
public static boolean isSecurityEnabled() {
ensureInitialized();
return useKerberos;
}
/**
* Information about the logged in user.
*/
private static UserGroupInformation loginUser = null;
private static String keytabPrincipal = null;
private static String keytabFile = null;
private final Subject subject;
private static final String OS_LOGIN_MODULE_NAME;
private static final Class<? extends Principal> OS_PRINCIPAL_CLASS;
private static final boolean windows =
System.getProperty("os.name").startsWith("Windows");
static {
if (windows) {
OS_LOGIN_MODULE_NAME = "com.sun.security.auth.module.NTLoginModule";
OS_PRINCIPAL_CLASS = NTUserPrincipal.class;
} else {
OS_LOGIN_MODULE_NAME = "com.sun.security.auth.module.UnixLoginModule";
OS_PRINCIPAL_CLASS = UnixPrincipal.class;
}
}
/**
* A JAAS configuration that defines the login modules that we want
* to use for login.
*/
private static class HadoopConfiguration
extends javax.security.auth.login.Configuration {
private static final String SIMPLE_CONFIG_NAME = "hadoop-simple";
private static final String USER_KERBEROS_CONFIG_NAME =
"hadoop-user-kerberos";
private static final String KEYTAB_KERBEROS_CONFIG_NAME =
"hadoop-keytab-kerberos";
private static final AppConfigurationEntry OS_SPECIFIC_LOGIN =
new AppConfigurationEntry(OS_LOGIN_MODULE_NAME,
LoginModuleControlFlag.REQUIRED,
new HashMap<String,String>());
private static final AppConfigurationEntry HADOOP_LOGIN =
new AppConfigurationEntry(HadoopLoginModule.class.getName(),
LoginModuleControlFlag.REQUIRED,
new HashMap<String,String>());
private static final Map<String,String> USER_KERBEROS_OPTIONS =
new HashMap<String,String>();
static {
USER_KERBEROS_OPTIONS.put("doNotPrompt", "true");
USER_KERBEROS_OPTIONS.put("useTicketCache", "true");
String ticketCache = System.getenv("KRB5CCNAME");
if (ticketCache != null) {
USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache);
}
}
private static final AppConfigurationEntry USER_KERBEROS_LOGIN =
new AppConfigurationEntry(Krb5LoginModule.class.getName(),
LoginModuleControlFlag.OPTIONAL,
USER_KERBEROS_OPTIONS);
private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS =
new HashMap<String,String>();
static {
KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
}
private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
new AppConfigurationEntry(Krb5LoginModule.class.getName(),
LoginModuleControlFlag.REQUIRED,
KEYTAB_KERBEROS_OPTIONS);
private static final AppConfigurationEntry[] SIMPLE_CONF =
new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN};
private static final AppConfigurationEntry[] USER_KERBEROS_CONF =
new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN,
HADOOP_LOGIN};
private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN};
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
if (SIMPLE_CONFIG_NAME.equals(appName)) {
return SIMPLE_CONF;
} else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) {
return USER_KERBEROS_CONF;
} else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) {
KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal);
return KEYTAB_KERBEROS_CONF;
}
return null;
}
}
/**
* Create a UserGroupInformation for the given subject.
* This does not change the subject or acquire new credentials.
* @param subject the user's subject
*/
UserGroupInformation(Subject subject) {
this.subject = subject;
}
/**
* Return the current user, including any doAs in the current stack.
* @return the current user
* @throws IOException if login fails
*/
public static UserGroupInformation getCurrentUser() throws IOException {
AccessControlContext context = AccessController.getContext();
Subject subject = Subject.getSubject(context);
return subject == null ? getLoginUser() : new UserGroupInformation(subject);
}
/**
* Get the currently logged in user.
* @return the logged in user
* @throws IOException if login fails
*/
public synchronized
static UserGroupInformation getLoginUser() throws IOException {
if (loginUser == null) {
try {
LoginContext login;
if (isSecurityEnabled()) {
login = new LoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME);
} else {
login = new LoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME);
}
login.login();
loginUser = new UserGroupInformation(login.getSubject());
String tokenFile = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
if (tokenFile != null && isSecurityEnabled()) {
TokenStorage.readTokensAndLoadInUGI(tokenFile, new Configuration(), loginUser);
}
} catch (LoginException le) {
throw new IOException("failure to login", le);
}
}
return loginUser;
}
/**
* Log a user in from a keytab file. Loads a user identity from a keytab
* file and login them in. They become the currently logged-in user.
* @param user the principal name to load from the keytab
* @param path the path to the keytab file
* @throws IOException if the keytab file can't be read
*/
public synchronized
static void loginUserFromKeytab(String user,
String path
) throws IOException {
if (!isSecurityEnabled())
return;
keytabFile = path;
keytabPrincipal = user;
try {
LoginContext login =
new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME);
login.login();
loginUser = new UserGroupInformation(login.getSubject());
} catch (LoginException le) {
throw new IOException("Login failure for " + user + " from keytab " +
path, le);
}
}
/**
* Create a user from a login name. It is intended to be used for remote
* users in RPC, since it won't have any credentials.
* @param user the full user principal name, must not be empty or null
* @return the UserGroupInformation for the remote user.
*/
public static UserGroupInformation createRemoteUser(String user) {
if (user == null || "".equals(user)) {
throw new IllegalArgumentException("Null user");
}
Subject subject = new Subject();
subject.getPrincipals().add(new User(user));
return new UserGroupInformation(subject);
}
/**
* This class is used for storing the groups for testing. It stores a local
* map that has the translation of usernames to groups.
*/
private static class TestingGroups extends Groups {
private final Map<String, List<String>> userToGroupsMapping =
new HashMap<String,List<String>>();
private TestingGroups() {
super(new org.apache.hadoop.conf.Configuration());
}
@Override
public List<String> getGroups(String user) {
List<String> result = userToGroupsMapping.get(user);
if (result == null) {
result = new ArrayList<String>();
}
return result;
}
private void setUserGroups(String user, String[] groups) {
userToGroupsMapping.put(user, Arrays.asList(groups));
}
}
/**
* Create a UGI for testing HDFS and MapReduce
* @param user the full user principal name
* @param userGroups the names of the groups that the user belongs to
* @return a fake user for running unit tests
*/
public static UserGroupInformation createUserForTesting(String user,
String[] userGroups) {
ensureInitialized();
UserGroupInformation ugi = createRemoteUser(user);
// make sure that the testing object is setup
if (!(groups instanceof TestingGroups)) {
groups = new TestingGroups();
}
// add the user groups
((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
return ugi;
}
/**
* Get the user's login name.
* @return the user's name up to the first '/' or '@'.
*/
public String getShortUserName() {
for (User p: subject.getPrincipals(User.class)) {
return p.getShortName();
}
return null;
}
/**
* Get the user's full principal name.
* @return the user's full principal name.
*/
public String getUserName() {
for (User p: subject.getPrincipals(User.class)) {
return p.getName();
}
return null;
}
/**
* Add a token to this UGI
*
* @param token Token to be added
* @return true on successful add of new token
*/
public synchronized boolean addToken(Token<? extends TokenIdentifier> token) {
return subject.getPrivateCredentials().add(token);
}
/**
* Obtain the collection of tokens associated with this user.
*
* @return an unmodifiable collection of tokens associated with user
*/
@SuppressWarnings("unchecked")
public synchronized <Ident extends TokenIdentifier>
Collection<Token<Ident>> getTokens() {
Set<Object> creds = subject.getPrivateCredentials();
List<Token<Ident>> result = new ArrayList<Token<Ident>>(creds.size());
for(Object o: creds) {
if (o instanceof Token) {
result.add((Token<Ident>) o);
}
}
return Collections.unmodifiableList(result);
}
/**
* Get the group names for this user.
* @return the list of users with the primary group first. If the command
* fails, it returns an empty list.
*/
public synchronized String[] getGroupNames() {
ensureInitialized();
try {
List<String> result = groups.getGroups(getShortUserName());
return result.toArray(new String[result.size()]);
} catch (IOException ie) {
LOG.warn("No groups available for user " + getShortUserName());
return new String[0];
}
}
/**
* Return the username.
*/
@Override
public String toString() {
return getUserName();
}
/**
* Compare the subjects to see if they are equal to each other.
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o == null || getClass() != o.getClass()) {
return false;
} else {
return subject.equals(((UserGroupInformation) o).subject);
}
}
/**
* Return the hash of the subject.
*/
@Override
public int hashCode() {
return subject.hashCode();
}
/**
* Get the underlying subject from this ugi.
* @return the subject that represents this user.
*/
protected Subject getSubject() {
return subject;
}
/**
* Run the given action as the user.
* @param <T> the return type of the run method
* @param action the method to execute
* @return the value from the run method
*/
public <T> T doAs(PrivilegedAction<T> action) {
return Subject.doAs(subject, action);
}
/**
* Run the given action as the user, potentially throwing an exception.
* @param <T> the return type of the run method
* @param action the method to execute
* @return the value from the run method
* @throws IOException if the action throws an IOException
* @throws Error if the action throws an Error
* @throws RuntimeException if the action throws a RuntimeException
* @throws InterruptedException if the action throws an InterruptedException
* @throws UndeclaredThrowableException if the action throws something else
*/
public <T> T doAs(PrivilegedExceptionAction<T> action
) throws IOException, InterruptedException {
try {
return Subject.doAs(subject, action);
} catch (PrivilegedActionException pae) {
Throwable cause = pae.getCause();
if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof InterruptedException) {
throw (InterruptedException) cause;
} else {
throw new UndeclaredThrowableException(pae,"Unknown exception in doAs");
}
}
}
private void print() throws IOException {
System.out.println("User: " + getUserName());
System.out.print("Group Ids: ");
System.out.println();
String[] groups = getGroupNames();
System.out.print("Groups: ");
for(int i=0; i < groups.length; i++) {
System.out.print(groups[i] + " ");
}
System.out.println();
}
/**
* A test method to print out the current user's UGI.
* @param args if there are two arguments, read the user from the keytab
* and print it out.
* @throws Exception
*/
public static void main(String [] args) throws Exception {
System.out.println("Getting UGI for current user");
UserGroupInformation ugi = getCurrentUser();
ugi.print();
System.out.println("UGI: " + ugi);
System.out.println("============================================================");
if (args.length == 2) {
System.out.println("Getting UGI from keytab....");
loginUserFromKeytab(args[0], args[1]);
getCurrentUser().print();
System.out.println("Keytab: " + ugi);
}
}
}
| false | true | private static synchronized void initialize(Configuration conf) {
String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
if ("simple".equals(value)) {
useKerberos = false;
} else if (value == null || "kerberos".equals(value)) {
useKerberos = true;
} else {
throw new IllegalArgumentException("Invalid attribute value for " +
HADOOP_SECURITY_AUTHENTICATION +
" of " + value);
}
// If we haven't set up testing groups, use the configuration to find it
if (!(groups instanceof TestingGroups)) {
groups = Groups.getUserToGroupsMappingService(conf);
}
// Set the configuration for JAAS to be the Hadoop configuration.
// This is done here rather than a static initializer to avoid a
// circular dependence.
javax.security.auth.login.Configuration.setConfiguration
(new HadoopConfiguration());
isInitialized = true;
}
| private static synchronized void initialize(Configuration conf) {
String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
if (value == null || "simple".equals(value)) {
useKerberos = false;
} else if ("kerberos".equals(value)) {
useKerberos = true;
} else {
throw new IllegalArgumentException("Invalid attribute value for " +
HADOOP_SECURITY_AUTHENTICATION +
" of " + value);
}
// If we haven't set up testing groups, use the configuration to find it
if (!(groups instanceof TestingGroups)) {
groups = Groups.getUserToGroupsMappingService(conf);
}
// Set the configuration for JAAS to be the Hadoop configuration.
// This is done here rather than a static initializer to avoid a
// circular dependence.
javax.security.auth.login.Configuration.setConfiguration
(new HadoopConfiguration());
isInitialized = true;
}
|
diff --git a/src/main/java/org/iplantc/de/client/views/windows/PipelineEditorWindow.java b/src/main/java/org/iplantc/de/client/views/windows/PipelineEditorWindow.java
index 19b3a7ef..65cc0587 100644
--- a/src/main/java/org/iplantc/de/client/views/windows/PipelineEditorWindow.java
+++ b/src/main/java/org/iplantc/de/client/views/windows/PipelineEditorWindow.java
@@ -1,104 +1,106 @@
package org.iplantc.de.client.views.windows;
import org.iplantc.core.pipelineBuilder.client.json.autobeans.Pipeline;
import org.iplantc.core.pipelines.client.presenter.PipelineViewPresenter;
import org.iplantc.core.pipelines.client.views.PipelineView;
import org.iplantc.core.pipelines.client.views.PipelineViewImpl;
import org.iplantc.core.uicommons.client.info.IplantAnnouncer;
import org.iplantc.core.uicommons.client.models.WindowState;
import org.iplantc.de.client.I18N;
import org.iplantc.de.client.views.windows.configs.ConfigFactory;
import org.iplantc.de.client.views.windows.configs.PipelineEditorWindowConfig;
import org.iplantc.de.client.views.windows.configs.WindowConfig;
import com.google.gwt.user.client.Command;
import com.google.web.bindery.autobean.shared.Splittable;
import com.sencha.gxt.widget.core.client.Dialog;
import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton;
import com.sencha.gxt.widget.core.client.box.MessageBox;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
public class PipelineEditorWindow extends IplantWindowBase {
private final PipelineView.Presenter presenter;
private String initPipelineJson;
private boolean close_after_save;
public PipelineEditorWindow(WindowConfig config) {
super(null, null);
setHeadingText(I18N.DISPLAY.pipeline());
setSize("900", "500"); //$NON-NLS-1$ //$NON-NLS-2$
setMinWidth(640);
setMinHeight(440);
PipelineView view = new PipelineViewImpl();
presenter = new PipelineViewPresenter(view, new PublishCallbackCommand());
if (config instanceof PipelineEditorWindowConfig) {
PipelineEditorWindowConfig pipelineConfig = (PipelineEditorWindowConfig)config;
Pipeline pipeline = pipelineConfig.getPipeline();
if (pipeline != null) {
presenter.setPipeline(pipeline);
initPipelineJson = presenter.getPublishJson(pipeline);
} else {
Splittable serviceWorkflowJson = pipelineConfig.getServiceWorkflowJson();
- initPipelineJson = serviceWorkflowJson.getPayload();
+ if (serviceWorkflowJson != null) {
+ initPipelineJson = serviceWorkflowJson.getPayload();
+ }
presenter.setPipeline(serviceWorkflowJson);
}
}
presenter.go(this);
close_after_save = false;
}
class PublishCallbackCommand implements Command {
@Override
public void execute() {
IplantAnnouncer.getInstance().schedule(I18N.DISPLAY.publishWorkflowSuccess());
if (close_after_save) {
close_after_save = false;
PipelineEditorWindow.super.hide();
}
}
}
@Override
public void hide() {
if (initPipelineJson != null
&& !initPipelineJson.equals(presenter.getPublishJson(presenter.getPipeline()))) {
MessageBox box = new MessageBox(I18N.DISPLAY.save(), "");
box.setPredefinedButtons(PredefinedButton.YES, PredefinedButton.NO, PredefinedButton.CANCEL);
box.setIcon(MessageBox.ICONS.question());
box.setMessage(I18N.DISPLAY.unsavedChanges());
box.addHideHandler(new HideHandler() {
@Override
public void onHide(HideEvent event) {
Dialog btn = (Dialog)event.getSource();
if (btn.getHideButton().getText().equalsIgnoreCase(PredefinedButton.NO.toString())) {
PipelineEditorWindow.super.hide();
}
if (btn.getHideButton().getText().equalsIgnoreCase(PredefinedButton.YES.toString())) {
presenter.saveOnClose();
close_after_save = true;
}
}
});
box.show();
} else {
PipelineEditorWindow.super.hide();
}
}
@Override
public WindowState getWindowState() {
PipelineEditorWindowConfig configData = ConfigFactory.workflowIntegrationWindowConfig();
configData.setPipeline(presenter.getPipeline());
return createWindowState(configData);
}
}
| true | true | public PipelineEditorWindow(WindowConfig config) {
super(null, null);
setHeadingText(I18N.DISPLAY.pipeline());
setSize("900", "500"); //$NON-NLS-1$ //$NON-NLS-2$
setMinWidth(640);
setMinHeight(440);
PipelineView view = new PipelineViewImpl();
presenter = new PipelineViewPresenter(view, new PublishCallbackCommand());
if (config instanceof PipelineEditorWindowConfig) {
PipelineEditorWindowConfig pipelineConfig = (PipelineEditorWindowConfig)config;
Pipeline pipeline = pipelineConfig.getPipeline();
if (pipeline != null) {
presenter.setPipeline(pipeline);
initPipelineJson = presenter.getPublishJson(pipeline);
} else {
Splittable serviceWorkflowJson = pipelineConfig.getServiceWorkflowJson();
initPipelineJson = serviceWorkflowJson.getPayload();
presenter.setPipeline(serviceWorkflowJson);
}
}
presenter.go(this);
close_after_save = false;
}
| public PipelineEditorWindow(WindowConfig config) {
super(null, null);
setHeadingText(I18N.DISPLAY.pipeline());
setSize("900", "500"); //$NON-NLS-1$ //$NON-NLS-2$
setMinWidth(640);
setMinHeight(440);
PipelineView view = new PipelineViewImpl();
presenter = new PipelineViewPresenter(view, new PublishCallbackCommand());
if (config instanceof PipelineEditorWindowConfig) {
PipelineEditorWindowConfig pipelineConfig = (PipelineEditorWindowConfig)config;
Pipeline pipeline = pipelineConfig.getPipeline();
if (pipeline != null) {
presenter.setPipeline(pipeline);
initPipelineJson = presenter.getPublishJson(pipeline);
} else {
Splittable serviceWorkflowJson = pipelineConfig.getServiceWorkflowJson();
if (serviceWorkflowJson != null) {
initPipelineJson = serviceWorkflowJson.getPayload();
}
presenter.setPipeline(serviceWorkflowJson);
}
}
presenter.go(this);
close_after_save = false;
}
|
diff --git a/src/fitnesse/components/ClassPathBuilderTest.java b/src/fitnesse/components/ClassPathBuilderTest.java
index 466369c02..aa2262c7c 100644
--- a/src/fitnesse/components/ClassPathBuilderTest.java
+++ b/src/fitnesse/components/ClassPathBuilderTest.java
@@ -1,153 +1,153 @@
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
package fitnesse.components;
import fitnesse.testutil.RegexTestCase;
import fitnesse.util.FileUtil;
import fitnesse.wiki.*;
public class ClassPathBuilderTest extends RegexTestCase
{
private WikiPage root;
private ClassPathBuilder builder;
String pathSeparator = System.getProperty("path.separator");
private PageCrawler crawler;
private WikiPagePath somePagePath;
private static final String TEST_DIR = "testDir";
public void setUp() throws Exception
{
root = InMemoryPage.makeRoot("RooT");
crawler = root.getPageCrawler();
builder = new ClassPathBuilder();
somePagePath = PathParser.parse("SomePage");
}
public void testGetClasspath() throws Exception
{
crawler.addPage(root, PathParser.parse("TestPage"),
"!path fitnesse.jar\n" +
"!path my.jar");
String expected = "fitnesse.jar" + pathSeparator + "my.jar";
assertEquals(expected, builder.getClasspath(root.getChildPage("TestPage")));
}
public void testGetPaths_OneLevel() throws Exception
{
String pageContent = "This is some content\n" +
"!path aPath\n" +
"end of conent\n";
WikiPage root = InMemoryPage.makeRoot("RooT");
WikiPage page = crawler.addPage(root, PathParser.parse("ClassPath"), pageContent);
String path = builder.getClasspath(page);
assertEquals("aPath", path);
}
public void testGetClassPathMultiLevel() throws Exception
{
WikiPage root = InMemoryPage.makeRoot("RooT");
crawler.addPage(root, PathParser.parse("ProjectOne"),
"!path path2\n" +
"!path path 3");
crawler.addPage(root, PathParser.parse("ProjectOne.TesT"), "!path path1");
String cp = builder.getClasspath(crawler.getPage(root, PathParser.parse("ProjectOne.TesT")));
assertSubString("path1", cp);
assertSubString("path2", cp);
assertSubString("\"path 3\"", cp);
}
public void testLinearClassPath() throws Exception
{
WikiPage root = InMemoryPage.makeRoot("RooT");
WikiPage superPage = crawler.addPage(root, PathParser.parse("SuperPage"), "!path superPagePath");
WikiPage subPage = crawler.addPage(superPage, PathParser.parse("SubPage"), "!path subPagePath");
String cp = builder.getClasspath(subPage);
assertEquals("subPagePath" + pathSeparator + "superPagePath", cp);
}
public void testGetClassPathFromPageThatDoesntExist() throws Exception
{
String classPath = makeClassPathFromSimpleStructure("somePath");
assertEquals("somePath", classPath);
}
private String makeClassPathFromSimpleStructure(String path) throws Exception
{
PageData data = root.getData();
data.setContent("!path " + path);
root.commit(data);
crawler = root.getPageCrawler();
crawler.setDeadEndStrategy(new MockingPageCrawler());
WikiPage page = crawler.getPage(root, somePagePath);
String classPath = builder.getClasspath(page);
return classPath;
}
public void testThatPathsWithSpacesGetQuoted() throws Exception
{
crawler.addPage(root, somePagePath, "!path Some File.jar");
crawler = root.getPageCrawler();
crawler.setDeadEndStrategy(new MockingPageCrawler());
WikiPage page = crawler.getPage(root, somePagePath);
assertEquals("\"Some File.jar\"", builder.getClasspath(page));
crawler.addPage(root, somePagePath, "!path somefile.jar\n!path Some Dir/someFile.jar");
assertEquals("somefile.jar" + pathSeparator + "\"Some Dir/someFile.jar\"", builder.getClasspath(page));
}
public void testWildCardExpansion() throws Exception
{
try
{
makeSampleFiles();
String classPath = makeClassPathFromSimpleStructure("testDir/*.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/*.dll");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("two\\.dll", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/one*");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("oneA", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/**.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
- assertHasRegexp("subdir/sub1\\.jar", classPath);
- assertHasRegexp("subdir/sub2\\.jar", classPath);
+ assertHasRegexp("subdir(?:\\\\|/)sub1\\.jar", classPath);
+ assertHasRegexp("subdir(?:\\\\|/)sub2\\.jar", classPath);
}
finally
{
deleteSampleFiles();
}
}
public static void makeSampleFiles()
{
FileUtil.makeDir(TEST_DIR);
FileUtil.createFile(TEST_DIR + "/one.jar", "");
FileUtil.createFile(TEST_DIR + "/two.jar", "");
FileUtil.createFile(TEST_DIR + "/one.dll", "");
FileUtil.createFile(TEST_DIR + "/two.dll", "");
FileUtil.createFile(TEST_DIR + "/oneA", "");
FileUtil.createFile(TEST_DIR + "/twoA", "");
FileUtil.createDir(TEST_DIR + "/subdir");
FileUtil.createFile(TEST_DIR + "/subdir/sub1.jar", "");
FileUtil.createFile(TEST_DIR + "/subdir/sub2.jar", "");
FileUtil.createFile(TEST_DIR + "/subdir/sub1.dll", "");
FileUtil.createFile(TEST_DIR + "/subdir/sub2.dll", "");
}
public static void deleteSampleFiles()
{
FileUtil.deleteFileSystemDirectory(TEST_DIR);
}
}
| true | true | public void testWildCardExpansion() throws Exception
{
try
{
makeSampleFiles();
String classPath = makeClassPathFromSimpleStructure("testDir/*.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/*.dll");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("two\\.dll", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/one*");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("oneA", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/**.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
assertHasRegexp("subdir/sub1\\.jar", classPath);
assertHasRegexp("subdir/sub2\\.jar", classPath);
}
finally
{
deleteSampleFiles();
}
}
| public void testWildCardExpansion() throws Exception
{
try
{
makeSampleFiles();
String classPath = makeClassPathFromSimpleStructure("testDir/*.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/*.dll");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("two\\.dll", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/one*");
assertHasRegexp("one\\.dll", classPath);
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("oneA", classPath);
classPath = makeClassPathFromSimpleStructure("testDir/**.jar");
assertHasRegexp("one\\.jar", classPath);
assertHasRegexp("two\\.jar", classPath);
assertHasRegexp("subdir(?:\\\\|/)sub1\\.jar", classPath);
assertHasRegexp("subdir(?:\\\\|/)sub2\\.jar", classPath);
}
finally
{
deleteSampleFiles();
}
}
|
diff --git a/tests/frontend/org/voltdb/regressionsuites/TestSystemProcedureSuite.java b/tests/frontend/org/voltdb/regressionsuites/TestSystemProcedureSuite.java
index a21def92f..7abc1c54c 100644
--- a/tests/frontend/org/voltdb/regressionsuites/TestSystemProcedureSuite.java
+++ b/tests/frontend/org/voltdb/regressionsuites/TestSystemProcedureSuite.java
@@ -1,662 +1,663 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.regressionsuites;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import org.voltdb.BackendTarget;
import org.voltdb.SysProcSelector;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.iv2.TxnEgo;
import org.voltdb_testprocs.regressionsuites.malicious.GoSleep;
public class TestSystemProcedureSuite extends RegressionSuite {
private static int sites = 3;
private static int hosts = 2;
private static int kfactor = 1;
private static boolean hasLocalServer = false;
static final Class<?>[] PROCEDURES =
{
GoSleep.class
};
public TestSystemProcedureSuite(String name) {
super(name);
}
public void testPing() throws IOException, ProcCallException {
Client client = getClient();
ClientResponse cr = client.callProcedure("@Ping");
assertEquals(ClientResponse.SUCCESS, cr.getStatus());
}
public void testInvalidProcedureName() throws IOException {
Client client = getClient();
try {
client.callProcedure("@SomeInvalidSysProcName", "1", "2");
}
catch (Exception e2) {
assertEquals("Procedure @SomeInvalidSysProcName was not found", e2.getMessage());
return;
}
fail("Expected exception.");
}
private final String m_loggingConfig =
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
"<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">" +
"<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\">" +
"<appender name=\"Console\" class=\"org.apache.log4j.ConsoleAppender\">" +
"<param name=\"Target\" value=\"System.out\" />" +
"<layout class=\"org.apache.log4j.TTCCLayout\">" +
"</layout>" +
"</appender>" +
"<appender name=\"Async\" class=\"org.apache.log4j.AsyncAppender\">" +
"<param name=\"Blocking\" value=\"true\" />" +
"<appender-ref ref=\"Console\" /> " +
"</appender>" +
"<root>" +
"<priority value=\"info\" />" +
"<appender-ref ref=\"Async\" />" +
"</root>" +
"</log4j:configuration>";
public void testUpdateLogging() throws Exception {
Client client = getClient();
VoltTable results[] = null;
results = client.callProcedure("@UpdateLogging", m_loggingConfig).getResults();
for (VoltTable result : results) {
assertEquals( 0, result.asScalarLong());
}
}
public void testPromoteMaster() throws Exception {
Client client = getClient();
try {
client.callProcedure("@Promote");
fail();
}
catch (ProcCallException pce) {
assertEquals(ClientResponse.GRACEFUL_FAILURE, pce.getClientResponse().getStatus());
}
}
public void testStatistics() throws Exception {
Client client = getClient();
//
// initiator selector
//
VoltTable results[] = null;
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test initiators table: " + results[0].toString());
//Now two entries because client affinity also does a query
assertEquals(2, results[0].getRowCount());
int counts = 0;
while (results[0].advanceRow()) {
String procName = results[0].getString("PROCEDURE_NAME");
if (procName.equals("@SystemCatalog")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
} else if (procName.equals("@Statistics")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
}
}
assertEquals(2, counts);
//
// invalid selector
//
try {
// No selector at all.
client.callProcedure("@Statistics");
fail();
}
catch (ProcCallException ex) {
// All badness gets turned into ProcCallExceptions, so we need
// to check specifically for this error, otherwise things that
// crash the cluster also turn into ProcCallExceptions and don't
// trigger failure (ENG-2347)
assertEquals("VOLTDB ERROR: PROCEDURE Statistics EXPECTS 3 PARAMS, BUT RECEIVED 1",
ex.getMessage());
}
try {
// Invalid selector
client.callProcedure("@Statistics", "garbage", 0);
fail();
}
catch (ProcCallException ex) {}
//
// Partition count
//
results = client.callProcedure("@Statistics", SysProcSelector.PARTITIONCOUNT.name(), 0).getResults();
assertEquals( 1, results.length);
assertTrue( results[0] != null);
assertEquals( 1, results[0].getRowCount());
assertEquals( 1, results[0].getColumnCount());
assertEquals( VoltType.INTEGER, results[0].getColumnType(0));
assertTrue( results[0].advanceRow());
final int siteCount = (int)results[0].getLong(0);
assertTrue (siteCount == TestSystemProcedureSuite.sites);
//
// table
//
results = client.callProcedure("@Statistics", "table", 0).getResults();
// one aggregate table returned
assertTrue(results.length == 1);
// with 10 rows per site. Can be two values depending on the test scenario of cluster vs. local.
assertEquals(TestSystemProcedureSuite.hosts * TestSystemProcedureSuite.sites * 3, results[0].getRowCount());
System.out.println("Test statistics table: " + results[0].toString());
results = client.callProcedure("@Statistics", "index", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
//
// memory
//
// give time to seed the stats cache?
Thread.sleep(1000);
results = client.callProcedure("@Statistics", "memory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
// alternate form
results = client.callProcedure("@Statistics", "nodememory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
//
// procedure
//
// 3 seconds translates to 3 billion nanos, which overflows internal
// values (ENG-1039)
//It's possible that the nanosecond count goes backwards... so run this a couple
//of times to make sure the min value gets set
for (int ii = 0; ii < 3; ii++) {
results = client.callProcedure("GoSleep", 3000, 0, null).getResults();
}
results = client.callProcedure("@Statistics", "procedure", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test procedures table: " + results[0].toString());
VoltTable stats = results[0];
String procname = "blerg";
while (!procname.equals("org.voltdb_testprocs.regressionsuites.malicious.GoSleep")) {
stats.advanceRow();
procname = (String)stats.get("PROCEDURE", VoltType.STRING);
}
// Retrieve all statistics
long min_time = (Long)stats.get("MIN_EXECUTION_TIME", VoltType.BIGINT);
long max_time = (Long)stats.get("MAX_EXECUTION_TIME", VoltType.BIGINT);
long avg_time = (Long)stats.get("AVG_EXECUTION_TIME", VoltType.BIGINT);
long min_result_size = (Long)stats.get("MIN_RESULT_SIZE", VoltType.BIGINT);
long max_result_size = (Long)stats.get("MAX_RESULT_SIZE", VoltType.BIGINT);
long avg_result_size = (Long)stats.get("AVG_RESULT_SIZE", VoltType.BIGINT);
long min_parameter_set_size = (Long)stats.get("MIN_PARAMETER_SET_SIZE", VoltType.BIGINT);
long max_parameter_set_size = (Long)stats.get("MAX_PARAMETER_SET_SIZE", VoltType.BIGINT);
long avg_parameter_set_size = (Long)stats.get("AVG_PARAMETER_SET_SIZE", VoltType.BIGINT);
// Check for overflow
assertTrue("Failed MIN_EXECUTION_TIME > 0, value was: " + min_time,
min_time > 0);
assertTrue("Failed MAX_EXECUTION_TIME > 0, value was: " + max_time,
max_time > 0);
assertTrue("Failed AVG_EXECUTION_TIME > 0, value was: " + avg_time,
avg_time > 0);
assertTrue("Failed MIN_RESULT_SIZE > 0, value was: " + min_result_size,
min_result_size >= 0);
assertTrue("Failed MAX_RESULT_SIZE > 0, value was: " + max_result_size,
max_result_size >= 0);
assertTrue("Failed AVG_RESULT_SIZE > 0, value was: " + avg_result_size,
avg_result_size >= 0);
assertTrue("Failed MIN_PARAMETER_SET_SIZE > 0, value was: " + min_parameter_set_size,
min_parameter_set_size >= 0);
assertTrue("Failed MAX_PARAMETER_SET_SIZE > 0, value was: " + max_parameter_set_size,
max_parameter_set_size >= 0);
assertTrue("Failed AVG_PARAMETER_SET_SIZE > 0, value was: " + avg_parameter_set_size,
avg_parameter_set_size >= 0);
// check for reasonable values
assertTrue("Failed MIN_EXECUTION_TIME > 2,400,000,000ns, value was: " +
min_time,
min_time > 2400000000L);
assertTrue("Failed MAX_EXECUTION_TIME > 2,400,000,000ns, value was: " +
max_time,
max_time > 2400000000L);
assertTrue("Failed AVG_EXECUTION_TIME > 2,400,000,000ns, value was: " +
avg_time,
avg_time > 2400000000L);
assertTrue("Failed MIN_RESULT_SIZE < 1,000,000, value was: " +
min_result_size,
min_result_size < 1000000L);
assertTrue("Failed MAX_RESULT_SIZE < 1,000,000, value was: " +
max_result_size,
max_result_size < 1000000L);
assertTrue("Failed AVG_RESULT_SIZE < 1,000,000, value was: " +
avg_result_size,
avg_result_size < 1000000L);
assertTrue("Failed MIN_PARAMETER_SET_SIZE < 1,000,000, value was: " +
min_parameter_set_size,
min_parameter_set_size < 1000000L);
assertTrue("Failed MAX_PARAMETER_SET_SIZE < 1,000,000, value was: " +
max_parameter_set_size,
max_parameter_set_size < 1000000L);
assertTrue("Failed AVG_PARAMETER_SET_SIZE < 1,000,000, value was: " +
avg_parameter_set_size,
avg_parameter_set_size < 1000000L);
//
// iostats
//
results = client.callProcedure("@Statistics", "iostats", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test iostats table: " + results[0].toString());
//
// TOPO
//
if (VoltDB.checkTestEnvForIv2()) {
results = client.callProcedure("@Statistics", "TOPO", 0).getResults();
// one aggregate table returned
- assertEquals(1, results.length);
+ assertEquals(2, results.length);
System.out.println("Test TOPO table: " + results[0].toString());
+ System.out.println("Test TOPO table: " + results[1].toString());
VoltTable topo = results[0];
// Make sure we can find the MPI, at least
boolean found = false;
while (topo.advanceRow()) {
if ((int)topo.getLong("Partition") == TxnEgo.MP_PARTITIONID) {
found = true;
}
}
assertTrue(found);
}
}
//
// planner statistics
//
public void testPlannerStatistics() throws Exception {
Client client = getClient();
// Clear the interval statistics
VoltTable[] results = client.callProcedure("@Statistics", "planner", 1).getResults();
assertEquals(1, results.length);
// Invoke a few select queries a few times to get some cache hits and misses,
// and to exceed the sampling frequency.
// This does not use level 2 cache (parameterization) or trigger failures.
for (String query : new String[] {
"select * from warehouse",
"select * from new_order",
"select * from item",
}) {
for (int i = 0; i < 10; i++) {
client.callProcedure("@AdHoc", query).getResults();
assertEquals(1, results.length);
}
}
// Get the final interval statistics
results = client.callProcedure("@Statistics", "planner", 1).getResults();
assertEquals(1, results.length);
System.out.println("Test planner table: " + results[0].toString());
VoltTable stats = results[0];
// Sample the statistics
List<Long> siteIds = new ArrayList<Long>();
int cache1_level = 0;
int cache2_level = 0;
int cache1_hits = 0;
int cache2_hits = 0;
int cache_misses = 0;
long plan_time_min_min = Long.MAX_VALUE;
long plan_time_max_max = Long.MIN_VALUE;
long plan_time_avg_tot = 0;
int failures = 0;
while (stats.advanceRow()) {
cache1_level += (Integer)stats.get("CACHE1_LEVEL", VoltType.INTEGER);
cache2_level += (Integer)stats.get("CACHE2_LEVEL", VoltType.INTEGER);
cache1_hits += (Integer)stats.get("CACHE1_HITS", VoltType.INTEGER);
cache2_hits += (Integer)stats.get("CACHE2_HITS", VoltType.INTEGER);
cache_misses += (Integer)stats.get("CACHE_MISSES", VoltType.INTEGER);
plan_time_min_min = Math.min(plan_time_min_min, (Long)stats.get("PLAN_TIME_MIN", VoltType.BIGINT));
plan_time_max_max = Math.max(plan_time_max_max, (Long)stats.get("PLAN_TIME_MAX", VoltType.BIGINT));
plan_time_avg_tot += (Long)stats.get("PLAN_TIME_AVG", VoltType.BIGINT);
failures += (Integer)stats.get("FAILURES", VoltType.INTEGER);
siteIds.add((Long)stats.get("SITE_ID", VoltType.BIGINT));
}
// Check for reasonable results
int globalPlanners = 0;
assertTrue("Failed siteIds count >= 2", siteIds.size() >= 2);
for (long siteId : siteIds) {
if (siteId == -1) {
globalPlanners++;
}
}
assertTrue("Global planner sites not 1, value was: " + globalPlanners, globalPlanners == 1);
assertTrue("Failed total CACHE1_LEVEL > 0, value was: " + cache1_level, cache1_level > 0);
assertTrue("Failed total CACHE1_LEVEL < 1,000,000, value was: " + cache1_level, cache1_level < 1000000);
assertTrue("Failed total CACHE2_LEVEL >= 0, value was: " + cache2_level, cache2_level >= 0);
assertTrue("Failed total CACHE2_LEVEL < 1,000,000, value was: " + cache2_level, cache2_level < 1000000);
assertTrue("Failed total CACHE1_HITS > 0, value was: " + cache1_hits, cache1_hits > 0);
assertTrue("Failed total CACHE1_HITS < 1,000,000, value was: " + cache1_hits, cache1_hits < 1000000);
assertTrue("Failed total CACHE2_HITS == 0, value was: " + cache2_hits, cache2_hits == 0);
assertTrue("Failed total CACHE2_HITS < 1,000,000, value was: " + cache2_hits, cache2_hits < 1000000);
assertTrue("Failed total CACHE_MISSES > 0, value was: " + cache_misses, cache_misses > 0);
assertTrue("Failed total CACHE_MISSES < 1,000,000, value was: " + cache_misses, cache_misses < 1000000);
assertTrue("Failed min PLAN_TIME_MIN > 0, value was: " + plan_time_min_min, plan_time_min_min > 0);
assertTrue("Failed total PLAN_TIME_MIN < 100,000,000,000, value was: " + plan_time_min_min, plan_time_min_min < 100000000000L);
assertTrue("Failed max PLAN_TIME_MAX > 0, value was: " + plan_time_max_max, plan_time_max_max > 0);
assertTrue("Failed total PLAN_TIME_MAX < 100,000,000,000, value was: " + plan_time_max_max, plan_time_max_max < 100000000000L);
assertTrue("Failed total PLAN_TIME_AVG > 0, value was: " + plan_time_avg_tot, plan_time_avg_tot > 0);
assertTrue("Failed total FAILURES == 0, value was: " + failures, failures == 0);
}
//public void testShutdown() {
// running @shutdown kills the JVM.
// not sure how to test this.
// }
// covered by TestSystemInformationSuite
/*public void testSystemInformation() throws IOException, ProcCallException {
Client client = getClient();
VoltTable results[] = client.callProcedure("@SystemInformation").getResults();
assertEquals(1, results.length);
System.out.println(results[0]);
}*/
// Pretty lame test but at least invoke the procedure.
// "@Quiesce" is used more meaningfully in TestExportSuite.
public void testQuiesce() throws IOException, ProcCallException {
Client client = getClient();
VoltTable results[] = client.callProcedure("@Quiesce").getResults();
assertEquals(1, results.length);
results[0].advanceRow();
assertEquals(results[0].get(0, VoltType.BIGINT), new Long(0));
}
public void testLoadMultipartitionTableAndIndexStats() throws IOException {
Client client = getClient();
// try the failure case first
try {
client.callProcedure("@LoadMultipartitionTable", "DOES_NOT_EXIST", null, 1);
fail();
} catch (ProcCallException ex) {}
// make a TPCC warehouse table
VoltTable partitioned_table = new VoltTable(
new VoltTable.ColumnInfo("W_ID", org.voltdb.VoltType.SMALLINT),
new VoltTable.ColumnInfo("W_NAME", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_STREET_1", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_STREET_2", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_CITY", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_STATE", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_ZIP", org.voltdb.VoltType.get((byte)9)),
new VoltTable.ColumnInfo("W_TAX",org.voltdb.VoltType.get((byte)8)),
new VoltTable.ColumnInfo("W_YTD", org.voltdb.VoltType.get((byte)8))
);
for (int i = 1; i < 21; i++) {
Object[] row = new Object[] {new Short((short) i),
"name_" + i,
"street1_" + i,
"street2_" + i,
"city_" + i,
"ma",
"zip_" + i,
new Double(i),
new Double(i)};
partitioned_table.addRow(row);
}
// make a TPCC item table
VoltTable replicated_table =
new VoltTable(new VoltTable.ColumnInfo("I_ID", VoltType.INTEGER),
new VoltTable.ColumnInfo("I_IM_ID", VoltType.INTEGER),
new VoltTable.ColumnInfo("I_NAME", VoltType.STRING),
new VoltTable.ColumnInfo("I_PRICE", VoltType.FLOAT),
new VoltTable.ColumnInfo("I_DATA", VoltType.STRING));
for (int i = 1; i < 21; i++) {
Object[] row = new Object[] {i,
i,
"name_" + i,
new Double(i),
"data_" + i};
replicated_table.addRow(row);
}
try {
try {
client.callProcedure("@LoadMultipartitionTable", "WAREHOUSE",
partitioned_table);
fail();
} catch (ProcCallException e) {}
client.callProcedure("@LoadMultipartitionTable", "ITEM",
replicated_table);
VoltTable results[] = client.callProcedure("@Statistics", "table", 0).getResults();
int foundItem = 0;
System.out.println(results[0]);
// Check that tables loaded correctly
while(results[0].advanceRow()) {
if (results[0].getString("TABLE_NAME").equals("ITEM"))
{
++foundItem;
//Different values depending on local cluster vs. single process hence ||
assertEquals(20, results[0].getLong("TUPLE_COUNT"));
}
}
assertEquals(6, foundItem);
VoltTable indexStats =
client.callProcedure("@Statistics", "INDEX", 0).getResults()[0];
System.out.println(indexStats);
long memorySum = 0;
while (indexStats.advanceRow()) {
memorySum += indexStats.getLong("MEMORY_ESTIMATE");
}
/*
* It takes about a minute to spin through this 1000 times.
* Should definitely give a 1 second tick time to fire
*/
long indexMemorySum = 0;
for (int ii = 0; ii < 1000; ii++) {
indexMemorySum = 0;
indexStats = client.callProcedure("@Statistics", "MEMORY", 0).getResults()[0];
System.out.println(indexStats);
while (indexStats.advanceRow()) {
indexMemorySum += indexStats.getLong("INDEXMEMORY");
}
boolean success = indexMemorySum != 120;//That is a row count, not memory usage
if (success) {
success = memorySum == indexMemorySum;
if (success) {
return;
}
}
Thread.sleep(1);
}
assertTrue(indexMemorySum != 120);//That is a row count, not memory usage
assertEquals(memorySum, indexMemorySum);
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
// verify that these commands don't blow up
public void testProfCtl() throws Exception {
Client client = getClient();
//
// SAMPLER_START
//
ClientResponse resp = client.callProcedure("@ProfCtl", "SAMPLER_START");
VoltTable vt = resp.getResults()[0];
boolean foundResponse = false;
while (vt.advanceRow()) {
if (!vt.getString("Result").equalsIgnoreCase("sampler_start")) {
fail();
}
foundResponse = true;
}
assertTrue(foundResponse);
//
// GPERF_ENABLE
//
resp = client.callProcedure("@ProfCtl", "GPERF_ENABLE");
vt = resp.getResults()[0];
foundResponse = false;
while (vt.advanceRow()) {
if (vt.getString("Result").equalsIgnoreCase("GPERF_ENABLE")) {
foundResponse = true;
}
else {
assertTrue(vt.getString("Result").equalsIgnoreCase("GPERF_NOOP"));
}
}
assertTrue(foundResponse);
//
// GPERF_DISABLE
//
resp = client.callProcedure("@ProfCtl", "GPERF_DISABLE");
vt = resp.getResults()[0];
foundResponse = false;
while (vt.advanceRow()) {
if (vt.getString("Result").equalsIgnoreCase("gperf_disable")) {
foundResponse = true;
}
else {
assertTrue(vt.getString("Result").equalsIgnoreCase("GPERF_NOOP"));
}
}
assertTrue(foundResponse);
//
// garbage
//
resp = client.callProcedure("@ProfCtl", "MakeAPony");
vt = resp.getResults()[0];
assertTrue(true);
}
//
// Build a list of the tests to be run. Use the regression suite
// helpers to allow multiple backends.
// JUnit magic that uses the regression suite helper classes.
//
static public Test suite() throws IOException {
VoltServerConfig config = null;
MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestSystemProcedureSuite.class);
// Not really using TPCC functionality but need a database.
// The testLoadMultipartitionTable procedure assumes partitioning
// on warehouse id.
VoltProjectBuilder project = new VoltProjectBuilder();
project.addLiteralSchema(
"CREATE TABLE WAREHOUSE (\n" +
" W_ID SMALLINT DEFAULT '0' NOT NULL,\n" +
" W_NAME VARCHAR(16) DEFAULT NULL,\n" +
" W_STREET_1 VARCHAR(32) DEFAULT NULL,\n" +
" W_STREET_2 VARCHAR(32) DEFAULT NULL,\n" +
" W_CITY VARCHAR(32) DEFAULT NULL,\n" +
" W_STATE VARCHAR(2) DEFAULT NULL,\n" +
" W_ZIP VARCHAR(9) DEFAULT NULL,\n" +
" W_TAX FLOAT DEFAULT NULL,\n" +
" W_YTD FLOAT DEFAULT NULL,\n" +
" CONSTRAINT W_PK_TREE PRIMARY KEY (W_ID)\n" +
");\n" +
"CREATE TABLE ITEM (\n" +
" I_ID INTEGER DEFAULT '0' NOT NULL,\n" +
" I_IM_ID INTEGER DEFAULT NULL,\n" +
" I_NAME VARCHAR(32) DEFAULT NULL,\n" +
" I_PRICE FLOAT DEFAULT NULL,\n" +
" I_DATA VARCHAR(64) DEFAULT NULL,\n" +
" CONSTRAINT I_PK_TREE PRIMARY KEY (I_ID)\n" +
");\n" +
"CREATE TABLE NEW_ORDER (\n" +
" NO_W_ID SMALLINT DEFAULT '0' NOT NULL\n" +
");\n");
project.addPartitionInfo("WAREHOUSE", "W_ID");
project.addPartitionInfo("NEW_ORDER", "NO_W_ID");
project.addProcedures(PROCEDURES);
/*config = new LocalCluster("sysproc-twosites.jar", 2, 1, 0,
BackendTarget.NATIVE_EE_JNI);
((LocalCluster) config).setHasLocalServer(false);
config.compile(project);
builder.addServerConfig(config);*/
/*
* Add a cluster configuration for sysprocs too
*/
config = new LocalCluster("sysproc-cluster.jar", TestSystemProcedureSuite.sites, TestSystemProcedureSuite.hosts, TestSystemProcedureSuite.kfactor,
BackendTarget.NATIVE_EE_JNI);
((LocalCluster) config).setHasLocalServer(hasLocalServer);
boolean success = config.compile(project);
assertTrue(success);
builder.addServerConfig(config);
return builder;
}
}
| false | true | public void testStatistics() throws Exception {
Client client = getClient();
//
// initiator selector
//
VoltTable results[] = null;
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test initiators table: " + results[0].toString());
//Now two entries because client affinity also does a query
assertEquals(2, results[0].getRowCount());
int counts = 0;
while (results[0].advanceRow()) {
String procName = results[0].getString("PROCEDURE_NAME");
if (procName.equals("@SystemCatalog")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
} else if (procName.equals("@Statistics")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
}
}
assertEquals(2, counts);
//
// invalid selector
//
try {
// No selector at all.
client.callProcedure("@Statistics");
fail();
}
catch (ProcCallException ex) {
// All badness gets turned into ProcCallExceptions, so we need
// to check specifically for this error, otherwise things that
// crash the cluster also turn into ProcCallExceptions and don't
// trigger failure (ENG-2347)
assertEquals("VOLTDB ERROR: PROCEDURE Statistics EXPECTS 3 PARAMS, BUT RECEIVED 1",
ex.getMessage());
}
try {
// Invalid selector
client.callProcedure("@Statistics", "garbage", 0);
fail();
}
catch (ProcCallException ex) {}
//
// Partition count
//
results = client.callProcedure("@Statistics", SysProcSelector.PARTITIONCOUNT.name(), 0).getResults();
assertEquals( 1, results.length);
assertTrue( results[0] != null);
assertEquals( 1, results[0].getRowCount());
assertEquals( 1, results[0].getColumnCount());
assertEquals( VoltType.INTEGER, results[0].getColumnType(0));
assertTrue( results[0].advanceRow());
final int siteCount = (int)results[0].getLong(0);
assertTrue (siteCount == TestSystemProcedureSuite.sites);
//
// table
//
results = client.callProcedure("@Statistics", "table", 0).getResults();
// one aggregate table returned
assertTrue(results.length == 1);
// with 10 rows per site. Can be two values depending on the test scenario of cluster vs. local.
assertEquals(TestSystemProcedureSuite.hosts * TestSystemProcedureSuite.sites * 3, results[0].getRowCount());
System.out.println("Test statistics table: " + results[0].toString());
results = client.callProcedure("@Statistics", "index", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
//
// memory
//
// give time to seed the stats cache?
Thread.sleep(1000);
results = client.callProcedure("@Statistics", "memory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
// alternate form
results = client.callProcedure("@Statistics", "nodememory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
//
// procedure
//
// 3 seconds translates to 3 billion nanos, which overflows internal
// values (ENG-1039)
//It's possible that the nanosecond count goes backwards... so run this a couple
//of times to make sure the min value gets set
for (int ii = 0; ii < 3; ii++) {
results = client.callProcedure("GoSleep", 3000, 0, null).getResults();
}
results = client.callProcedure("@Statistics", "procedure", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test procedures table: " + results[0].toString());
VoltTable stats = results[0];
String procname = "blerg";
while (!procname.equals("org.voltdb_testprocs.regressionsuites.malicious.GoSleep")) {
stats.advanceRow();
procname = (String)stats.get("PROCEDURE", VoltType.STRING);
}
// Retrieve all statistics
long min_time = (Long)stats.get("MIN_EXECUTION_TIME", VoltType.BIGINT);
long max_time = (Long)stats.get("MAX_EXECUTION_TIME", VoltType.BIGINT);
long avg_time = (Long)stats.get("AVG_EXECUTION_TIME", VoltType.BIGINT);
long min_result_size = (Long)stats.get("MIN_RESULT_SIZE", VoltType.BIGINT);
long max_result_size = (Long)stats.get("MAX_RESULT_SIZE", VoltType.BIGINT);
long avg_result_size = (Long)stats.get("AVG_RESULT_SIZE", VoltType.BIGINT);
long min_parameter_set_size = (Long)stats.get("MIN_PARAMETER_SET_SIZE", VoltType.BIGINT);
long max_parameter_set_size = (Long)stats.get("MAX_PARAMETER_SET_SIZE", VoltType.BIGINT);
long avg_parameter_set_size = (Long)stats.get("AVG_PARAMETER_SET_SIZE", VoltType.BIGINT);
// Check for overflow
assertTrue("Failed MIN_EXECUTION_TIME > 0, value was: " + min_time,
min_time > 0);
assertTrue("Failed MAX_EXECUTION_TIME > 0, value was: " + max_time,
max_time > 0);
assertTrue("Failed AVG_EXECUTION_TIME > 0, value was: " + avg_time,
avg_time > 0);
assertTrue("Failed MIN_RESULT_SIZE > 0, value was: " + min_result_size,
min_result_size >= 0);
assertTrue("Failed MAX_RESULT_SIZE > 0, value was: " + max_result_size,
max_result_size >= 0);
assertTrue("Failed AVG_RESULT_SIZE > 0, value was: " + avg_result_size,
avg_result_size >= 0);
assertTrue("Failed MIN_PARAMETER_SET_SIZE > 0, value was: " + min_parameter_set_size,
min_parameter_set_size >= 0);
assertTrue("Failed MAX_PARAMETER_SET_SIZE > 0, value was: " + max_parameter_set_size,
max_parameter_set_size >= 0);
assertTrue("Failed AVG_PARAMETER_SET_SIZE > 0, value was: " + avg_parameter_set_size,
avg_parameter_set_size >= 0);
// check for reasonable values
assertTrue("Failed MIN_EXECUTION_TIME > 2,400,000,000ns, value was: " +
min_time,
min_time > 2400000000L);
assertTrue("Failed MAX_EXECUTION_TIME > 2,400,000,000ns, value was: " +
max_time,
max_time > 2400000000L);
assertTrue("Failed AVG_EXECUTION_TIME > 2,400,000,000ns, value was: " +
avg_time,
avg_time > 2400000000L);
assertTrue("Failed MIN_RESULT_SIZE < 1,000,000, value was: " +
min_result_size,
min_result_size < 1000000L);
assertTrue("Failed MAX_RESULT_SIZE < 1,000,000, value was: " +
max_result_size,
max_result_size < 1000000L);
assertTrue("Failed AVG_RESULT_SIZE < 1,000,000, value was: " +
avg_result_size,
avg_result_size < 1000000L);
assertTrue("Failed MIN_PARAMETER_SET_SIZE < 1,000,000, value was: " +
min_parameter_set_size,
min_parameter_set_size < 1000000L);
assertTrue("Failed MAX_PARAMETER_SET_SIZE < 1,000,000, value was: " +
max_parameter_set_size,
max_parameter_set_size < 1000000L);
assertTrue("Failed AVG_PARAMETER_SET_SIZE < 1,000,000, value was: " +
avg_parameter_set_size,
avg_parameter_set_size < 1000000L);
//
// iostats
//
results = client.callProcedure("@Statistics", "iostats", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test iostats table: " + results[0].toString());
//
// TOPO
//
if (VoltDB.checkTestEnvForIv2()) {
results = client.callProcedure("@Statistics", "TOPO", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test TOPO table: " + results[0].toString());
VoltTable topo = results[0];
// Make sure we can find the MPI, at least
boolean found = false;
while (topo.advanceRow()) {
if ((int)topo.getLong("Partition") == TxnEgo.MP_PARTITIONID) {
found = true;
}
}
assertTrue(found);
}
}
| public void testStatistics() throws Exception {
Client client = getClient();
//
// initiator selector
//
VoltTable results[] = null;
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
results = client.callProcedure("@Statistics", "INITIATOR", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test initiators table: " + results[0].toString());
//Now two entries because client affinity also does a query
assertEquals(2, results[0].getRowCount());
int counts = 0;
while (results[0].advanceRow()) {
String procName = results[0].getString("PROCEDURE_NAME");
if (procName.equals("@SystemCatalog")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
} else if (procName.equals("@Statistics")) {
assertEquals( 1, results[0].getLong("INVOCATIONS"));
counts++;
}
}
assertEquals(2, counts);
//
// invalid selector
//
try {
// No selector at all.
client.callProcedure("@Statistics");
fail();
}
catch (ProcCallException ex) {
// All badness gets turned into ProcCallExceptions, so we need
// to check specifically for this error, otherwise things that
// crash the cluster also turn into ProcCallExceptions and don't
// trigger failure (ENG-2347)
assertEquals("VOLTDB ERROR: PROCEDURE Statistics EXPECTS 3 PARAMS, BUT RECEIVED 1",
ex.getMessage());
}
try {
// Invalid selector
client.callProcedure("@Statistics", "garbage", 0);
fail();
}
catch (ProcCallException ex) {}
//
// Partition count
//
results = client.callProcedure("@Statistics", SysProcSelector.PARTITIONCOUNT.name(), 0).getResults();
assertEquals( 1, results.length);
assertTrue( results[0] != null);
assertEquals( 1, results[0].getRowCount());
assertEquals( 1, results[0].getColumnCount());
assertEquals( VoltType.INTEGER, results[0].getColumnType(0));
assertTrue( results[0].advanceRow());
final int siteCount = (int)results[0].getLong(0);
assertTrue (siteCount == TestSystemProcedureSuite.sites);
//
// table
//
results = client.callProcedure("@Statistics", "table", 0).getResults();
// one aggregate table returned
assertTrue(results.length == 1);
// with 10 rows per site. Can be two values depending on the test scenario of cluster vs. local.
assertEquals(TestSystemProcedureSuite.hosts * TestSystemProcedureSuite.sites * 3, results[0].getRowCount());
System.out.println("Test statistics table: " + results[0].toString());
results = client.callProcedure("@Statistics", "index", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
//
// memory
//
// give time to seed the stats cache?
Thread.sleep(1000);
results = client.callProcedure("@Statistics", "memory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
// alternate form
results = client.callProcedure("@Statistics", "nodememory", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Node memory statistics table: " + results[0].toString());
//
// procedure
//
// 3 seconds translates to 3 billion nanos, which overflows internal
// values (ENG-1039)
//It's possible that the nanosecond count goes backwards... so run this a couple
//of times to make sure the min value gets set
for (int ii = 0; ii < 3; ii++) {
results = client.callProcedure("GoSleep", 3000, 0, null).getResults();
}
results = client.callProcedure("@Statistics", "procedure", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test procedures table: " + results[0].toString());
VoltTable stats = results[0];
String procname = "blerg";
while (!procname.equals("org.voltdb_testprocs.regressionsuites.malicious.GoSleep")) {
stats.advanceRow();
procname = (String)stats.get("PROCEDURE", VoltType.STRING);
}
// Retrieve all statistics
long min_time = (Long)stats.get("MIN_EXECUTION_TIME", VoltType.BIGINT);
long max_time = (Long)stats.get("MAX_EXECUTION_TIME", VoltType.BIGINT);
long avg_time = (Long)stats.get("AVG_EXECUTION_TIME", VoltType.BIGINT);
long min_result_size = (Long)stats.get("MIN_RESULT_SIZE", VoltType.BIGINT);
long max_result_size = (Long)stats.get("MAX_RESULT_SIZE", VoltType.BIGINT);
long avg_result_size = (Long)stats.get("AVG_RESULT_SIZE", VoltType.BIGINT);
long min_parameter_set_size = (Long)stats.get("MIN_PARAMETER_SET_SIZE", VoltType.BIGINT);
long max_parameter_set_size = (Long)stats.get("MAX_PARAMETER_SET_SIZE", VoltType.BIGINT);
long avg_parameter_set_size = (Long)stats.get("AVG_PARAMETER_SET_SIZE", VoltType.BIGINT);
// Check for overflow
assertTrue("Failed MIN_EXECUTION_TIME > 0, value was: " + min_time,
min_time > 0);
assertTrue("Failed MAX_EXECUTION_TIME > 0, value was: " + max_time,
max_time > 0);
assertTrue("Failed AVG_EXECUTION_TIME > 0, value was: " + avg_time,
avg_time > 0);
assertTrue("Failed MIN_RESULT_SIZE > 0, value was: " + min_result_size,
min_result_size >= 0);
assertTrue("Failed MAX_RESULT_SIZE > 0, value was: " + max_result_size,
max_result_size >= 0);
assertTrue("Failed AVG_RESULT_SIZE > 0, value was: " + avg_result_size,
avg_result_size >= 0);
assertTrue("Failed MIN_PARAMETER_SET_SIZE > 0, value was: " + min_parameter_set_size,
min_parameter_set_size >= 0);
assertTrue("Failed MAX_PARAMETER_SET_SIZE > 0, value was: " + max_parameter_set_size,
max_parameter_set_size >= 0);
assertTrue("Failed AVG_PARAMETER_SET_SIZE > 0, value was: " + avg_parameter_set_size,
avg_parameter_set_size >= 0);
// check for reasonable values
assertTrue("Failed MIN_EXECUTION_TIME > 2,400,000,000ns, value was: " +
min_time,
min_time > 2400000000L);
assertTrue("Failed MAX_EXECUTION_TIME > 2,400,000,000ns, value was: " +
max_time,
max_time > 2400000000L);
assertTrue("Failed AVG_EXECUTION_TIME > 2,400,000,000ns, value was: " +
avg_time,
avg_time > 2400000000L);
assertTrue("Failed MIN_RESULT_SIZE < 1,000,000, value was: " +
min_result_size,
min_result_size < 1000000L);
assertTrue("Failed MAX_RESULT_SIZE < 1,000,000, value was: " +
max_result_size,
max_result_size < 1000000L);
assertTrue("Failed AVG_RESULT_SIZE < 1,000,000, value was: " +
avg_result_size,
avg_result_size < 1000000L);
assertTrue("Failed MIN_PARAMETER_SET_SIZE < 1,000,000, value was: " +
min_parameter_set_size,
min_parameter_set_size < 1000000L);
assertTrue("Failed MAX_PARAMETER_SET_SIZE < 1,000,000, value was: " +
max_parameter_set_size,
max_parameter_set_size < 1000000L);
assertTrue("Failed AVG_PARAMETER_SET_SIZE < 1,000,000, value was: " +
avg_parameter_set_size,
avg_parameter_set_size < 1000000L);
//
// iostats
//
results = client.callProcedure("@Statistics", "iostats", 0).getResults();
// one aggregate table returned
assertEquals(1, results.length);
System.out.println("Test iostats table: " + results[0].toString());
//
// TOPO
//
if (VoltDB.checkTestEnvForIv2()) {
results = client.callProcedure("@Statistics", "TOPO", 0).getResults();
// one aggregate table returned
assertEquals(2, results.length);
System.out.println("Test TOPO table: " + results[0].toString());
System.out.println("Test TOPO table: " + results[1].toString());
VoltTable topo = results[0];
// Make sure we can find the MPI, at least
boolean found = false;
while (topo.advanceRow()) {
if ((int)topo.getLong("Partition") == TxnEgo.MP_PARTITIONID) {
found = true;
}
}
assertTrue(found);
}
}
|
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/schedules/ScheduledServiceTypeResourceHandler.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/schedules/ScheduledServiceTypeResourceHandler.java
index 11795b2e6..bdd3f05ae 100644
--- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/schedules/ScheduledServiceTypeResourceHandler.java
+++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/schedules/ScheduledServiceTypeResourceHandler.java
@@ -1,156 +1,155 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.rest.schedules;
import java.io.IOException;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Variant;
import org.sonatype.nexus.maven.tasks.SnapshotRemoverTask;
import org.sonatype.nexus.rest.model.ScheduledServiceTypePropertyResource;
import org.sonatype.nexus.rest.model.ScheduledServiceTypeResource;
import org.sonatype.nexus.rest.model.ScheduledServiceTypeResourceResponse;
import org.sonatype.nexus.tasks.ClearCacheTask;
import org.sonatype.nexus.tasks.PublishIndexesTask;
import org.sonatype.nexus.tasks.RebuildAttributesTask;
import org.sonatype.nexus.tasks.ReindexTask;
public class ScheduledServiceTypeResourceHandler
extends AbstractScheduledServiceResourceHandler
{
/**
* The default constructor.
*
* @param context
* @param request
* @param response
*/
public ScheduledServiceTypeResourceHandler( Context context, Request request, Response response )
{
super( context, request, response );
}
/**
* We are handling HTTP GETs.
*/
public boolean allowGet()
{
return true;
}
/**
* We create the List of Scheduled Services by getting them from Nexus App.
*/
public Representation getRepresentationHandler( Variant variant )
throws IOException
{
// TODO: This should be auto-discovered!
ScheduledServiceTypeResourceResponse response = new ScheduledServiceTypeResourceResponse();
ScheduledServiceTypeResource type = new ScheduledServiceTypeResource();
type.setId( PublishIndexesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
ScheduledServiceTypePropertyResource property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ReindexTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( RebuildAttributesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ClearCacheTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( ClearCacheTask.RESOURCE_STORE_PATH_KEY );
property.setName( "Repository path" );
property.setType( PROPERTY_TYPE_STRING );
- property
- .setHelpText( "Type in the repository path from which to clear caches recursively (ie. \"/\" for root or \"/org/apache\")" );
+ property.setHelpText( "Type in the repository path from which to clear caches recursively (ie. \"/\" for root or \"/org/apache\")" );
+ property.setRequired( true );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( SnapshotRemoverTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.MIN_SNAPSHOTS_TO_KEEP_KEY );
property.setName( "Minimum snapshot count" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
property.setHelpText( "Minimum number of snapshots to keep for one GAV." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.REMOVE_OLDER_THAN_DAYS_KEY );
property.setName( "Snapshot retention (days)" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
- property
- .setHelpText( "The job will purge all snapshots older than the entered number of days, but will obey to Min. count of snapshots to keep." );
+ property.setHelpText( "The job will purge all snapshots older than the entered number of days, but will obey to Min. count of snapshots to keep." );
type.addProperty( property );
response.addData( type );
return serialize( variant, response );
}
}
| false | true | public Representation getRepresentationHandler( Variant variant )
throws IOException
{
// TODO: This should be auto-discovered!
ScheduledServiceTypeResourceResponse response = new ScheduledServiceTypeResourceResponse();
ScheduledServiceTypeResource type = new ScheduledServiceTypeResource();
type.setId( PublishIndexesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
ScheduledServiceTypePropertyResource property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ReindexTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( RebuildAttributesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ClearCacheTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( ClearCacheTask.RESOURCE_STORE_PATH_KEY );
property.setName( "Repository path" );
property.setType( PROPERTY_TYPE_STRING );
property
.setHelpText( "Type in the repository path from which to clear caches recursively (ie. \"/\" for root or \"/org/apache\")" );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( SnapshotRemoverTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.MIN_SNAPSHOTS_TO_KEEP_KEY );
property.setName( "Minimum snapshot count" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
property.setHelpText( "Minimum number of snapshots to keep for one GAV." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.REMOVE_OLDER_THAN_DAYS_KEY );
property.setName( "Snapshot retention (days)" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
property
.setHelpText( "The job will purge all snapshots older than the entered number of days, but will obey to Min. count of snapshots to keep." );
type.addProperty( property );
response.addData( type );
return serialize( variant, response );
}
| public Representation getRepresentationHandler( Variant variant )
throws IOException
{
// TODO: This should be auto-discovered!
ScheduledServiceTypeResourceResponse response = new ScheduledServiceTypeResourceResponse();
ScheduledServiceTypeResource type = new ScheduledServiceTypeResource();
type.setId( PublishIndexesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
ScheduledServiceTypePropertyResource property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ReindexTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( RebuildAttributesTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( ClearCacheTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( ClearCacheTask.RESOURCE_STORE_PATH_KEY );
property.setName( "Repository path" );
property.setType( PROPERTY_TYPE_STRING );
property.setHelpText( "Type in the repository path from which to clear caches recursively (ie. \"/\" for root or \"/org/apache\")" );
property.setRequired( true );
type.addProperty( property );
response.addData( type );
type = new ScheduledServiceTypeResource();
type.setId( SnapshotRemoverTask.class.getName() );
type.setName( getServiceTypeName( type.getId() ) );
property = new ScheduledServiceTypePropertyResource();
property.setId( PublishIndexesTask.REPOSITORY_OR_GROUP_ID_KEY );
property.setName( "Repository/Group" );
property.setType( PROPERTY_TYPE_REPO_OR_GROUP );
property.setRequired( false );
property.setHelpText( "Select the repository or repository group to assign to this task. Making no selection will result in the task running for ALL repositories." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.MIN_SNAPSHOTS_TO_KEEP_KEY );
property.setName( "Minimum snapshot count" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
property.setHelpText( "Minimum number of snapshots to keep for one GAV." );
type.addProperty( property );
property = new ScheduledServiceTypePropertyResource();
property.setId( SnapshotRemoverTask.REMOVE_OLDER_THAN_DAYS_KEY );
property.setName( "Snapshot retention (days)" );
property.setType( PROPERTY_TYPE_NUMBER );
property.setRequired( true );
property.setHelpText( "The job will purge all snapshots older than the entered number of days, but will obey to Min. count of snapshots to keep." );
type.addProperty( property );
response.addData( type );
return serialize( variant, response );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.